(记录一下)STL的map底层实现一般是红黑树,会自动按照key排序,按照value排序好像也没有更好的方法了,只能将map转成vector<pair>再进行排序了~
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
vector<pair<int, int>> sort_by_value(const map<int, int>& m) {
vector<pair<int, int>> vec;
for (const auto& item: m) {
vec.push_back(item);
}
sort(vec.begin(), vec.end(), [](const pair<int, int> &p1, const pair<int, int> &p2) {
return p1.second < p2.second;
});
return vec;
}

本文介绍了如何在C++中使用STL Map,由于Map默认按Key排序,若要按照Value排序,需要将Map转换为其他数据结构并进行排序。

1990

被折叠的 条评论
为什么被折叠?



