我想在地图容器中使用仅值而不是键排序元素。怎么做?我知道地图可以按键值排序,但如何做到反之亦然。我在stackoverfrlow中发现了相同的问题。我喜欢这个解决方案。然而,我想澄清什么意思是转储在 pair< K,V> 。我不想为此创建特殊的结构,它不优雅。如何实现此解决方案?
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?
推荐答案为了将信息从std :: map转储到std :: vector,你可以使用std :: vector的构造函数,它需要两个迭代器。
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 签名:
bool myFunction(std::pair<K,V> first, std::pair<K,V> second);如果他们是正确的顺序(即第一个应该在第二个之前)返回true。
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).
此外,您可能需要请查看 boost :: bimap ,这看起来更适合您的问题。
Also, you might want to look at boost::bimap, which seems more attuned to your problem.
更多推荐
c ++,stl,map如何用值排序,而不是键
发布评论