Based on the idea of ββ@swegi, I implemented the solution in C ++ 11 using multimap :
map<int, int> m = {{1, 10}, {2, 5}, {4, 6}, {6, 1}}; multimap<int, int> mm; for(auto const &kv : m) mm.insert(make_pair(kv.second, kv.first));
Ideone Code
I also implemented a C ++ 11 solution based on @Chris idea using a vector of pairs. For proper sorting, I provide lambda expression as a comparison function:
map<int, int> m = {{1, 10}, {2, 5}, {4, 6}, {6, 1}}; using mypair = pair<int, int>; vector<mypair> v(begin(m), end(m)); sort(begin(v), end(v), [](const mypair& a, const mypair& b) { return a.second < b.second; }); for(auto const &p : v) cout << "m[" << p.first << "] = " << p.second << endl;
Ideon code
The first solution is more compact, but both solutions should have approximately the same performance. The insert in multimap has the value O (log n), but this needs to be done for n entries, resulting in O (n log n). Sorting the vector in the second solution also results in O (n log n).
I also tried @Chris's idea of ββusing a set of pairs. However, this will not work if the values ββare not all different. Using a functor that only compares the second element of a pair does not help. If you first enter make_pair(1, 1) into the set, and then try to insert make_pair(2, 1) , then the second pair will not be inserted, because both pairs are considered identical to this set. You can see this effect here on Ideone .