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

编程入门 行业动态 更新时间:2024-10-26 22:19:42
本文介绍了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如何用值排序,而不是键

本文发布于:2023-07-10 08:28:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1089842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何用   而不是   stl   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!