0
我写了一个自己的比较器的地图,并测试查找功能。但它似乎不起作用。代码如下所示,我想创建一个映射,其键类型是一对,值类型是一个int。当我运行代码时,它总是输出“not find”而不是地图中的某些值。有谁能告诉我为什么?地图与自定义比较器不工作
#include <iostream>
#include <map>
using namespace std;
struct Mycomp {
bool operator() (const pair<int, int> &a, const pair<int, int> &b) {
int firsta = a.first;
int seconda = a.second;
if(firsta > seconda) {
int temp = firsta;
firsta = seconda;
seconda = temp;
}
int firstb = b.first;
int secondb = b.second;
if(firstb > secondb) {
int temp = firstb;
firstb = secondb;
secondb = temp;
}
if(firsta != firstb)
return firsta <= firstb;
else
return seconda <= secondb;
}
};
int main(void) {
map<pair<int, int>, int, Mycomp> mymap;
mymap.insert(std::make_pair(std::make_pair(0, 1), 10));
mymap.insert(std::make_pair(std::make_pair(2, 3), 10));
auto it = mymap.find(std::make_pair(1, 0));
if(it == mymap.end())
out << "not find" << endl;
else
cout << it->second << endl;
return 0;
}
你比较不严格弱序。基本上,比较器应该模拟'<',而不是'<='。 – 2015-04-05 02:52:03
谢谢,你的评论帮助我很多。 – 2015-04-05 04:09:00