Martin
Martin

Reputation: 9369

Is it possible to specify an order to an unordered_map?

Is there really no guaranteed order in an unordered_map? I ask this because I would like to specify an order for an unorderded_map, so that it is possible to iterate the container from begin() to end() according to the specified order (while preserving the efficiency of an hashed access to single elements, globally speaking).

Upvotes: 0

Views: 124

Answers (2)

Xeo
Xeo

Reputation: 131789

You know, it has its name for a reason...

To actually give it an order, you'd need to implement your own hash that somehow gives you the wanted order.

Now, for a solution to your actual problem, you can just create a std::map from your std::unordered_map, and even with minimal overhead for the insert (no copies):

#include <iostream>
#include <unordered_map>
#include <map>
#include <functional>

int main()
{
    std::unordered_map<int, int> m;
    m[5] = 1;
    m[4] = 2;
    m[3] = 3;
    m[2] = 4;
    m[1] = 5;
    typedef std::reference_wrapper<const int> cref_int;
    typedef std::reference_wrapper<int> ref_int;
    std::map<cref_int, ref_int> ordered(m.begin(), m.end());
    for(auto it=ordered.begin(), ite=ordered.end(); it != ite; ++it){
        std::cout << it->second << '\n';
    }
}

Upvotes: 8

flownt
flownt

Reputation: 760

Of course not. If you need an order, use the regular map.

Upvotes: 5

Related Questions