简体   繁体   English

c ++,stl,map如何用值排序,而不是键

[英]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. 我在stackoverfrlow中发现了同样的问题。 I like this solution . 我喜欢这个解决方案 However I want clarify what does it mean "dump in pair<K,V> ". 但是我想弄清楚它是什么意思“转储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 :: map转储到std :: vector中,你可以使用带有两个迭代器的std :: vector的构造函数。

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: myFunction将是一个使用签名定义的函数:

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). 如果它们的顺序正确(即首先应该在第二个之前),它会返回true。 Return false when they are in the wrong order(ie second should be before first). 当它们处于错误的顺序时返回false(即第二个应该在第一个之前)。


Also, you might want to look at boost::bimap , which seems more attuned to your problem. 另外,你可能想看一下boost :: bimap ,这似乎更适合你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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