Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will std::multimap preserve the insert order if the key of 2 elements equal to each other?

Tags:

c++

stl

I am wondering whether this is true? If it is, is this behavior guaranteed by the c++ standard?

like image 489
Thomson Avatar asked Jul 28 '10 03:07

Thomson


People also ask

Does multimap preserve order?

The iteration order is preserved across non-distinct key values. For example, for the following multimap definition: Multimap<K, V> multimap = LinkedListMultimap. create(); multimap.

Are multimap values sorted?

Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys.

Does multimap allow duplicate keys?

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.

Does Unordered_map maintain insertion order?

No. It's called "unordered" for a reason. If you need to maintain an order of insertion, you've chosen an unsuitable data structure.


1 Answers

The elements in a std::map must have unique keys, so... no.

The std::multimap container allows multiple values mapped to one key. When iterating over a std::multimap the elements are ordered by key, but the order of elements having the same key is not specified.

Note that in the latest draft of the forthcoming C++0x standard (N3092), the relative ordering of elements with the same key is guaranteed (so, at some point, you'll be able to rely on this behavior).

like image 76
James McNellis Avatar answered Sep 27 '22 21:09

James McNellis