我试图unordered_map<int, int>按其值对 an 进行反向排序,但我不明白为什么它不能正常工作。
这是我正在使用的代码:
static bool comp(const pair<int,int>& a, const pair<int,int>& b) { return a.second < b.second; }
unordered_map<int,int> sort_map(unordered_map<int,int>& m) {
vector<pair<int,int>> v;
unordered_map<int,int> sorted_m;
for (const auto& it : m) {
v.push_back(it);
}
sort(v.begin(),v.end(),comp);
std::cout << "sorted vector:" << std::endl;
for (const auto& it : v) {
std::cout << it.first <<":" << it.second <<std::endl;
sorted_m.emplace(it);
}
return sorted_m;
}
Run Code Online (Sandbox Code Playgroud)
这是地图的输入示例:[5,-3,9,1,7,7,9,10,2,2,10,10,3,-1,3,7,-9,-1,3,3]
这是输出:
sorted vector:
-9:1
1:1
-3:1
5:1
-1:2
2:2
9:2
10:3
7:3
3:4
sorted …Run Code Online (Sandbox Code Playgroud)