简体   繁体   English

如何在C ++中根据另一个地图对地图排序?

[英]How do I sort a map according to another map in c++?

I have two maps: 我有两张地图:

map< T t, int v> map1;
map< T t, int v> map2;

how could I sort the map2 according to the value of map1? 如何根据map1的值对map2进行排序? (Or save the result to a vector?) Is there a simply way to achive this? (或将结果保存到向量?)有没有简单的方法可以达到此目的?

You cannot sort an std::map . 您不能对std::map排序。 The map is always kept in sorted order of keys. 映射始终按键的排序顺序保存。 This is an essential invariant of the data structure, and there's nothing you can do do mutate that. 这是数据结构的基本不变式,您无能为力。 Best you can do is to copy the map into a different container and rearrange that one, eg: 最好的办法是将地图复制到另一个容器中,然后重新排列该容器,例如:

std::vector<std::pair<T, int>> v(map1.begin(), map1.end());

As Kerrek said, you can simply construct a std::vector< std::pair< T, int> > from the begin and end iterator of your map, but this will also give you the keys and values. 正如Kerrek所说,您可以从地图的beginend迭代器简单地构造一个std::vector< std::pair< T, int> > ,但这也将为您提供键和值。 You can use std::transform to only get the values: 您可以使用std::transform仅获取值:

std::map<int, int> m = { {1,-1}, {2,-2} };
std::vector<int> v; v.reserve(m.size());
std::transform(m.begin(), m.end(), std::back_inserter(v), 
               [](const std::pair<const int, int>& p)
               { return p.second; });
// or
std::transform(m.begin(), m.end(), std::back_inserter(v), 
               std::bind(&std::pair<const int, int>::second, std::placeholders::_1));

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

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