rok*_*oku 1 c++ sorting dictionary unordered-map
我试图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 map:
3:4
10:3
9:2
2:2
-1:2
5:1
-3:1
1:1
7:3
-9:1
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,向量已正确排序,但是当我使用顺序时emplace(),顺序会变得混乱(7:3应该在之后10:3)。为什么会发生这种情况?
您无法控制 中元素的顺序unordered_map。这不是插入顺序。映射中元素的顺序是未指定的,并且在程序运行之间以及相同数据的不同插入模式之间可能会有所不同。
你很不幸地看到了一个和你想要的订单差不多的案例,让你觉得这是可能的。
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |