Reputation: 25560
I want to sort elements in map container using only values not key. how to do it? I know that map can sort by key value, but how to do vice versa. I found same question in stackoverfrlow. I like this solution. However I want clarify what does it mean "dump in pair<K,V>
". I don't want create special structure for that, it is not elegant. how do you implements this solution?
Upvotes: 4
Views: 12579
Reputation:
In order to dump the information from a std::map into a std::vector, you can use std::vector's constructor that takes two iterators.
std::vector<std::pair<K,V> > myVec(myMap.begin(), myMap.end());
You would then sort it with:
std::sort(myVec.begin(),myVec.end(),&myFunction);
myFunction
would be a function defined with the signature:
bool myFunction(std::pair<K,V> first, std::pair<K,V> second);
Have it return true if you they are in the right order(i.e. first should be before second). Return false when they are in the wrong order(i.e. second should be before first).
Also, you might want to look at boost::bimap, which seems more attuned to your problem.
Upvotes: 19