简体   繁体   English

c++ 设置结构,set.find() 函数产生错误“无效的比较器”

[英]c++ set with structs, set.find() function making error 'invalid comparator'

I make set of structs.我制作了一组结构。 My struct has one array with length 8 inside as pointer.我的结构有一个长度为 8 的数组作为指针。 If I insert some structs to the set, it's okay.如果我在集合中插入一些结构,就可以了。 But when I try to find, error('invalid comparator') occurs.但是当我尝试查找时,会发生错误('无效比较器')。 Here is my code.这是我的代码。

struct Key {
    int* arr;
};

bool operator<(const Key& a, const Key& b) {
    for (int i = 0; i < 8; i++) {
        if (a.arr[i] == b.arr[i]) {
            continue;
        }
        else {
            return a.arr[i] < b.arr[i];
        }
    }

    return true;
}

bool operator==(const Key& a, const Key& b) {
    for (int i = 0; i < 8; i++) {
        if (a.arr[i] != b.arr[i]) {
            return false;
        }
    }

    return true;
}


    set<Key> visit;
    visit.insert(initKey);

......

                Key key;
                key.arr = newcandidate;

                visit.find(key); -> trigger error.

I want to add arrays to somewhere.我想将数组添加到某个地方。 Then I want to find some arrays in there fastly.然后我想在那里快速找到一些数组。 So I try to use 'set' structures.所以我尝试使用“集合”结构。 What do I need to do to solve this problem?我需要做什么来解决这个问题? Thank you very much for your reading.非常感谢您的阅读。

You need to define properly only operator<.您只需要正确定义 operator<。 The operator== is not relevant to the set. operator== 与集合无关。 You should return false at last row.您应该在最后一行返回 false。 The relation is strict.关系是严格的。 It shouldn't be possible to have a < b and b < a, but your operator is defined to be a < a.应该不可能有 a < b 和 b < a,但是您的运算符被定义为 a < a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM