我正在尝试通过为它编写一个比较函数来使用标准排序函数对其中包含一组对的多图进行排序,但是我在其中遇到了一些错误。我正在尝试使用值对地图进行排序,然后再次使用键对其进行排序。比较功能导致一些错误。你能指出我在哪里出错了。
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
bool cmp(const pair<int,int>& a, const pair<int,int>& b)
{
return a.second < b.second;
}
int main() {
// multimap of int ssId, int phone numbers
multimap <int, int> m;
m.insert(make_pair(1, 8));
m.insert(make_pair(1, 5));
m.insert(make_pair(2, 4));
m.insert(make_pair(2, 3));
m.insert(make_pair(3, 1));
sort(m.begin(), m.end(), cmp);
return 0;
}
输出应该是这样的:
1 5
1 8
2 3
2 4
3 1
原文由 CVS 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 C++ 中没有直接的方法可以做到这一点,因为 multimap 是有序的,其顺序不能更改,但是有一个使用额外的 multimap 的解决方法。它会准确地输出你想要的。类似的方法适用于字符串到整数,反之亦然多图。