简体   繁体   中英

c++, stl, map how sort with value, not key

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 ?

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(ie first should be before second). Return false when they are in the wrong order(ie second should be before first).


Also, you might want to look at boost::bimap , which seems more attuned to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM