I have a map (for example, of character to integer). I insert values into this map one by one. For example, here are four insertions:
1: A -> 1
2: B -> 2
3: C -> 3
4: D -> 1
I would like to sort the map keys based on their associated values. So, at each insertion, I would have the sorted output:
1: A(1)
2: B(2), A(1)
3: C(3), B(2), A(1)
4: C(3), B(2), A(1), D(1)
Furthermore, I would like to be able to overwrite existing mappings to keep the keys (characters) unique. So a fifth insertion:
5: A -> 27
Would cause the sorted output to be:
5: A(27), C(3), B(2), D(1)
One way I can do this is using a multimap. The key of the multimap would be the integer, and the values would be the characters. Each insertion into the multimap would first need to check if the character is already present in the multimap, and remove that mapping before performing the insertion. The multimap keeps the keys ordered, so that takes care of the sorting.
Is there a faster way to do this? Is there a different, more efficient container that I should be using?
EDIT
Here's the C++ STL multimap I'm using. It's handy because it keeps its elements internally ordered.
Here's a related question. I'm trying to avoid doing what's suggested in the accepted solution: creating another map.