Search code examples
c++dictionaryiteratormultimap

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


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.