c++中map unordered_map按照value排序几种优雅的写法

我们首先假设我们要操作的mapunordered_map对象是m

第一种做法是先建立一个vector<pair<type, type>>的容器。

std::vector<std::pair<int, int>> tmp;
for (auto& i : m)
    tmp.push_back(i);

std::sort(tmp.begin(), tmp.end(), 
          [=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; });

第二种写法更加符合现代c++。首先建立一个临时map,然后通过transform函数将m中的元素insertertmp中。通过将map中元素的firstsecond交换达到,对value排序的目的。

std::map<int, int> tmp;
std::transform(m.begin(), m.end(), std::inserter(tmp, tmp.begin()), 
               [](std::pair<int, int> a) { return std::pair<int, int>(a.second, a.first); });

不过第二种写法要加头文件#include <algorithm>#include <iterator>c++中的transform有点类似于python中的map

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/80959968
今日推荐