CodingHero CodingHero - 12 days ago 5
C++ Question

Are c++ std::map<string,string> ordered?

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");


Thanks a lot.

Answer

are STL maps ordered?

Yes, a std::map<K,V> is ordered based on the key, K, using std::less<K> to compare objects, by default.

So if I iterate over it, it will iterate with the first insert string first?

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::vector or a std::list.

Comments