如何按 .second 参数对地图进行排序
如果我有一个从字符串到 int 的 stl 映射,并且我想打印所有已排序的 int 值 - 我该怎么做?
If i have a stl map from string to int and i want to print all the int values sorted - how can i do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于地图的实现,您无法按地图的值对地图进行排序。
如果你想以这样的排序顺序发出映射中的元素,那么你必须首先将映射内容转储到一个向量中(比如说)并对该向量进行排序:
或者,只需从映射中复制值,留下键,并直接对结果向量进行排序。
You cannot sort a map by its values due to the implementation of the map.
If you want to emit the elements in the map in such a sorted order then you have to first dump the map contents into a vector (say) and sort that vector:
Or alternatively, just copy the values from the map, leaving the keys, and sort the resulting vector directly.
您可以将所有值复制到向量中并对其进行排序。
You can copy all the values into vector and sort it.
您无法自动执行此操作。
std::map
使用第一个值(nomen omen 'key')对内容进行排序。相反,您可以使用
boost: :multi_index_container
。You cannot do this automatically.
std::map
uses first value (nomen omen 'key') to sort content.Instead, you can use
boost::multi_index_container
.如果您需要多次执行此操作,则保留两个单独的容器可能会更有效,例如您的地图和排序容器,例如
设置
或multiset
用于存储排序后的整数,而不必创建容器并即时对其进行排序。但随后你必须保持它们同步,这可能会变得很糟糕。您可以通过将它们包装在一个类中来封装它,或者更好地使用boost::multi_index_container
。If you need to do this multiple times, it might be more efficient to keep two separate containers, e.g. your map and a sorted container like
set
ormultiset
for storing the sorted ints, rather than having to create a container and sort it on the fly. But then you have to keep them synchronized, which could get mucky. You could encapsulate that by wrapping them in a class, or better yet use aboost::multi_index_container
.您无法对地图进行排序,它是一个关联容器,而不是顺序容器,并且关联容器按某种内部顺序排序。
如果您只想打印
int
值,可以将它们放入std::vector
中,对向量进行排序,然后打印值。You cannot sort a map, it's an associative container, not a sequential, and associated containers are sorted by some internal order.
If you want to only print the
int
values, you could put them into astd::vector
, sort the vector, and print the values.我宁愿将它们复制到
set
,而不是使用vector
:Instead of using a
vector
, I'd rather just copy them to aset<int>
: