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_mapwhere its key is the social security ID of a person and its value is a
std::stringwith 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.,
Naively, one would think to use
std::sortin order to sort the
std::unordered_mapaccording 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::sortwith a range of either a
std::unordered_setwill raise a compiler error.
- Why STL's unordered containers cannot be sorted by
- Is there a legitimate and efficient way to sort either a