C ++, stl, map how to sort by value, not key

I want to sort the elements in the map container using only values ​​that are not key. how to do it? I know that a map can be sorted by key value, but how to do the opposite. I found the same question in stackoverfrlow. I like this solution . However, I want to clarify that this means "reset to pair<K,V> ". I do not want to create a special structure for you, it is not elegant. How do you implement this solution ?

+4
source share
1 answer

To unload information from std :: map to std :: vector, you can use the std :: vector constructor, which takes two iterators.

 std::vector<std::pair<K,V> > myVec(myMap.begin(), myMap.end()); 

Then you sorted it with:

 std::sort(myVec.begin(),myVec.end(),&myFunction); 

myFunction will be a function defined with a signature:

 bool myFunction(std::pair<K,V> first, std::pair<K,V> second); 

Ask him to return true if you are in the correct order (that is, you must first be before the second). Return false when they are in the wrong order (that is, the second must be earlier).


Alternatively, you can look at boost :: bimap , which seems more customized to your problem.

+19
source

Source: https://habr.com/ru/post/1388080/


All Articles