I'll start by illustrating a simple use case example:
Consider the problem of a social security ID database, where in C++ code is modelled as a
std::unordered_map
where its key is the social security ID of a person and its value is astd::string
with the full-name of that person (e.g.,std::unordered_map<int, std::string> DB;
).Consider also, that there's a request for printing this database sorted in ascending order based on the person's ID (i.e.,
std::unordered_map
's key).Naively, one would think to use
std::sort
in order to sort thestd::unordered_map
according to the requested criteria and then print it, like the example code below:
std::sort(DB.begin(), DB.end());
for(auto p : DB) std::cout << "ID(" << p.first
<< ") - "
<< p.second
<< std::endl;
- However, this is not the case, because use of
std::sort
with a range of either astd::unordered_map
or astd::unordered_set
will raise a compiler error.
Questions:
- Why STL's unordered containers cannot be sorted by
std::sort
? - Is there a legitimate and efficient way to sort either a
std::unordered_map
or astd::unordered_set
?
unordered_*
are not. – Thrashersort
has no clue what container the iterators are from, the error is becausesort
requiresRandomAccessIterator
s while(unordered_)map|set
iterators areBiDirectionalIterator
s. 2) There's a reason those containers are named unordered_map|set
. If you want ordering use amap|set
– Eros