are STL maps ordered?
Specifically I need to know if std::map is ordered. So if I iterate over it, it will iterate with the first insert string first.
So will the below iterate A, C then B consistantly?
std::map<string,string> str_map;
str_map.insert(std::make_pair("A","Data"));
str_map.insert(std::make_pair("C","Data"));
str_map.insert(std::make_pair("B","Data"));
Yes, a
std::map<K,V>is ordered based on the key,K, usingstd::less<K>to compare objects, by default.No. It will iterate based on the sorted order, not the order that you inserted elements. In the case of
std::string, it sorts in lexicographic order (alphabetic order).If you want to iterate based on the insertion order, you’re better off using a sequence container, such as a
std::vectoror astd::list.