Iterating over std::map or std::multimap
suggest changeA std::map or a std::multimap can be traversed in the following ways:
std::multimap< int , int > mmp{ {1, 2}, {3, 4}, {6, 5}, {8, 9}, {3, 4}, {6, 7} };
//Range based loop - since C++11
for(const auto &x: mmp)
std::cout<< x.first <<":"<< x.second << std::endl;
//Forward iterator loop: from the first element to the last.
//The iterator type is std::multimap<int, int>::iterator.
for (auto it = mmp.begin(); it != mmp.end(); ++it)
std::cout<< it->first <<":"<< it->second << std::endl; //Do something with iterator
//Reverse-iterator loop: from the last element to the first.
//The iterator type is std::multimap<int, int>::reverse_iterator.
for (auto it = mmp.rbegin(); it != mmp.rend(); ++it)
std::cout<< it->first <<" "<< it->second << std::endl; //Do something with iterator
While iterating over a std::map or a std::multimap, the use of auto is preferred to avoid useless implicit conversions (see this SO answer for more details).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents