简体   繁体   English

std map和multimap迭代器是一样的吗?

[英]std map and multimap iterators are the same?

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;
}

Why do the two loops iterating over my_map yield the same results? 为什么在my_map迭代的两个循环my_map产生相同的结果? Is there not a difference between std::multimap::iterator and std::map::iterator? std :: multimap :: iterator和std :: map :: iterator之间没有区别吗?

It's quite possible that the implementation of std::multimap and std::map on your compiler use the same iterator, or something that's accidentally compatible. 编译器上std::multimapstd::map的实现很有可能使用相同的迭代器,或偶然兼容的迭代器。 That does not mean that this behavior is guaranteed. 并不意味着,这种行为得到了保证。 It could change in the next version of the compiler, not to mention using another compiler. 在下一版本的编译器中可能会更改,更不用说使用其他编译器了。

The iterators are not the same, but the ordering is the same I think. 迭代器并不相同,但是我认为顺序是相同的。 For multimap or map the element are ordered by its keys. 对于multimap mapmap ,元素按其键排序。 The order is determined by a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). 顺序由其内部比较对象(类型为Compare)指示的特定严格弱排序标准确定。

In your example, the orders of the keys are same for both cases. 在您的示例中,两种情况下键的顺序相同。 I guess that's why. 我想这就是原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM