Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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")); 
like image 901
CodingHero Avatar asked Jun 30 '12 14:06

CodingHero


People also ask

Are std::map ordered?

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

Does C++ map keep order?

C++ hash map and hash set which preserves the order of insertion. The ordered-map library provides a hash map and a hash set which preserve the order of insertion in a way similar to Python's OrderedDict. When iterating over the map, the values will be returned in the same order as they were inserted.

Does map allow duplicates in C++?

C++ Software Engineering Multi-map in C++ is an associative container like map. It internally store elements in key value pair. But unlike map which store only unique keys, multimap can have duplicate keys.

Is map already sorted C++?

By default, a Map in C++ is sorted in increasing order based on its key.


2 Answers

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.

like image 136
Oliver Charlesworth Avatar answered Oct 12 '22 20:10

Oliver Charlesworth


std::maps are sorted using either the given type's operator< or using a custom comparison function/functor if one is supplied as an argument to the constructor.

So no, when you iterate over the map, the first item you get won't be the one you inserted first - it will be the one that comes first alphabetically.

Of course for your sample code that doesn't make a difference because "A" is the first key you inserted and also the first one alphabetically.

like image 42
sepp2k Avatar answered Oct 12 '22 20:10

sepp2k