Question

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? Is there not a difference between std::multimap::iterator and std::map::iterator?

Was it helpful?

Solution

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. 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.

OTHER TIPS

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. The order is determined by a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

In your example, the orders of the keys are same for both cases. I guess that's why.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top