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 , using std::less<K> to compare objects, by default.
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.
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.
By default, a Map in C++ is sorted in increasing order based on its key.
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
.
std::map
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With