map键值 相等 怎么排序
时间: 2024-01-25 10:03:03 浏览: 19
如果你想对map的键进行排序,可以使用一个vector来存储键,然后使用sort函数进行排序。当两个键相等时,可以使用另一个函数来比较它们的值。
示例代码如下:
```c++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(const int& a, const int& b, const map<int, int>& m)
{
return m.at(a) < m.at(b);
}
int main()
{
map<int, int> m {{2, 30}, {1, 50}, {3, 20}, {4, 10}};
vector<int> keys;
for (const auto& p : m) {
keys.push_back(p.first);
}
sort(keys.begin(), keys.end(), [&](const int& a, const int& b) {
if (m.at(a) == m.at(b)) {
return a < b;
} else {
return compare(a, b, m);
}
});
for (const auto& k : keys) {
cout << k << ": " << m[k] << endl;
}
return 0;
}
```
这个程序首先创建一个map,然后使用一个vector来存储map的键。接下来,使用sort函数对键进行排序。当两个键的值相等时,使用compare函数来比较它们的值。compare函数使用map::at函数来查找键对应的值,并比较它们的大小。最后,按顺序输出键和对应的值。