【问题标题】:std map and multimap iterators are the same?std map 和 multimap 迭代器是一样的吗?
【发布时间】:2013-09-24 02:32:53
【问题描述】:
std::multimap<int, int> my_map;
for(int i=0; i<10; ++i)
{
    my_map.insert(std::pair<int, int>(i, i));
    my_map.insert(std::pair<int, int>(i, i));
}

std::multimap<int, int>::iterator it(my_map.begin());
std::multimap<int, int>::iterator end(my_map.end());
for(; it!=end; ++it)
{
    cout << it->first << " " << it->second << endl;
}

std::map<int, int>::iterator it(my_map.begin());
std::map<int, int>::iterator end(my_map.end());
for(; it!=end; ++it)
{
    cout << it->first << " " << it->second << endl;
}

为什么遍历my_map 的两个循环会产生相同的结果? std::multimap::iterator 和 std::map::iterator 没有区别吗?

【问题讨论】:

  • 您的代码有错误(迭代器类型和容器类型不匹配)。修复错误,谜团就会消失。理解错误代码的行为非常非常困难。
  • @DavidSchwartz 代码编译并运行良好。我想知道为什么会这样。
  • 它有一个错误。它不会像您期望的那样运行。这就是虫子的本质。修复错误,谜团就会消失。这就是程序员尽力避免错误的原因。

标签: c++ map iterator multimap


【解决方案1】:

很有可能在您的编译器上实现std::multimapstd::map 使用相同的迭代器,或者意外兼容的东西。 not 是否意味着这种行为是有保证的。它可能会在下一个版本的编译器中发生变化,更不用说使用另一个编译器了。

【讨论】:

    【解决方案2】:

    迭代器不一样,但我认为顺序是一样的。对于multimapmap,元素按其键排序。顺序由其内部比较对象(Compare 类型)指示的特定严格弱排序标准确定。

    在您的示例中,两种情况下键的顺序相同。我想这就是原因。

    【讨论】:

      猜你喜欢
      • 2012-03-11
      • 2023-03-05
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2012-09-30
      • 1970-01-01
      相关资源
      最近更新 更多