c ++,stl,map如何用值排序,而不是键 [英] c++, stl, map how sort with value, not key

查看:577
本文介绍了c ++,stl,map如何用值排序,而不是键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地图容器中使用仅值而不是键排序元素。怎么做?我知道地图可以按键值排序,但如何做到反之亦然。我在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如何用值排序,而不是键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆