使用自定义比较器的地图无效

时间:2015-04-05 02:45:48

标签: c++

我用自己的比较器写了一张地图,并测试了find函数。但似乎行不通。代码如下所示,我想创建一个映射,其键类型是一对,值类型是一个int。当我运行代码时,它总是输出"没有找到"而不是一些值存储在地图中。有谁可以告诉我为什么?

#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;
}

1 个答案:

答案 0 :(得分:0)

将@IgorTandetnik的评论转换为答案。

替换行:

if(firsta != firstb) 
    return firsta <= firstb;
else
    return seconda <= secondb;

通过

if(firsta != firstb) 
    return firsta < firstb;  // Use < not <=
else
    return seconda < secondb;
相关问题