map排序问题怎么解决
时间: 2023-07-31 12:10:58 浏览: 49
C++中的map是一种关联容器,其内部使用红黑树进行实现。由于红黑树的特性,map中的元素是有序的,按照键值从小到大排列。
如果需要按照值进行排序,可以将map中的键值对转换为pair对象,然后将所有pair对象存储在vector中。接着可以使用STL中的sort函数对vector进行排序,最后将排好序的pair对象重新插入到map中即可。
以下是代码示例:
```c++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second; // 按值从小到大排序
}
int main() {
map<int, int> m{{1, 4}, {2, 2}, {3, 5}, {4, 1}, {5, 3}};
vector<pair<int, int>> v(m.begin(), m.end());
sort(v.begin(), v.end(), cmp);
m.clear();
for(auto& p : v) {
m.insert(p);
}
for(auto& p : m) {
cout << p.first << " " << p.second << endl;
}
return 0;
}
```
输出结果为:
```
4 1
2 2
5 3
1 4
3 5
```