Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the order of unordered_map as we insert a new key

Tags:

c++

c++11

I inserted the elements to the unordered_map with this code:

    myMap.insert(std::make_pair("A", 10));
    myMap.insert(std::make_pair("B", 11));
    myMap.insert(std::make_pair("C", 12));
    myMap.insert(std::make_pair("D", 13));

But when I used this command to print the keys

for (const auto i : myMap)
{
    cout  << i.first << std::endl;
}

they are not in the same order as I inserted them.

Is it possible to keep the order?

like image 375
user1436187 Avatar asked Jan 28 '16 05:01

user1436187


People also ask

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.

Are Keys sorted in unordered_map?

An unordered_map is a hash container, that is, the keys are hashed. Inside of the container, they don't have the same representation as on the outside. Even the name implies that you can't sort it.

What happens if we insert duplicate key in unordered_map?

Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns 1 if an element with that key exists in the container, and zero otherwise.

In what order elements are stored in unordered_map?

map (like set) is an ordered sequence of unique keys whereas in unordered_map key can be stored in any order, so unordered.


2 Answers

No, it is not possible.

Usage of std::unordered_map doesn't give you any guarantee on element order.

If you want to keep elements sorted by map keys (as seems from your example) you should use std::map.

If you need to keep list of ordered pairs you can use std::vector<std::pair<std::string,int>>.

like image 110
Pustovalov Dmitry Avatar answered Oct 21 '22 14:10

Pustovalov Dmitry


Not with an unordered associative data structure. However, other data structures preserve order, such as std::map which keeps the data sorted by their keys. If you search Stackoverflow a little, you will find many solutions for a data structure with fast key-based lookup and ordered access, e.g. using boost::multi_index.

If it is just about adding values to a container, and taking them out in the order of insertion, then you can go with something that models a queue, e.g. std::dequeue. Just push_back to add a new value, and pop_front to remove the oldest value. If there is no need to remove the values from the container then just go with a std::vector.

like image 28
Jens Avatar answered Oct 21 '22 13:10

Jens