A junior colleague asked me about the following problem: given a
std::mapor
std::multimapof key to value pairs, sort it by values; or turn it into value to key mapping.
In order to solve this problem we need two data structures: the source
std::mapor
std::multimapof key to value pairs, and a second, output
std::multimapin which we will invert the pairs (
std::multimapbecause in the source different keys can point at the same value; the value in the source will become the key in the output, and
std::multimapwill handle duplicates).
The solution is to walk the source data structure of key to value pairs, and build the output data structure of value to key pairs.
Complete listing:
#include#include #include
Source (Key -> Value):
Program output.
2 -> 4
6 -> 8
8 -> 4
9 -> 6
9 -> 2
Output (Value -> Key):
2 -> 9
4 -> 2
4 -> 8
6 -> 9
8 -> 6
Program ended with exit code: 1