set::find() 不适用于用户定义的数据类型

set::find() not working with user define data type

当我搜索一个不在我的集合中的键时,find() 不是将迭代器返回到结束,而是将迭代器返回到另一个不等于键但存在于集合中的对象。

我不知道出了什么问题。

代码

class node{
public:
    int a, b;
    node(int a, int b):a(a), b(b){}

    bool operator>(const node &ob)const{
        return (this->b - this->a) > (ob.b - ob.a);     
    }

    bool operator==(const node &ob)const{
        return ((this->a == ob.a) && (this->b == ob.b));
    }
};

void print(set<node,greater<node>> &s){
    cout << "[ ";
    for(const node &ob: s){
        cout << "(" << ob.a << "," << ob.b << ") ";
    }

    cout <<"]\n--------------------------------" << endl;
}
set<node,greater<node>> s;                  
int main(){
    s.insert(node(0,3));
    s.insert(node(3,8));
    print(s);
    s.erase(node(3,8));
    cout << "After erasing (3, 8)" << endl;
    print(s);
    cout << "Searching for key (3,6)" << endl;
    set<node,greater<node>>::iterator i = s.find(node(3,6));
    if(i == s.end()){
        cout << "Not Found" << endl;
    }else{
        cout << "Found : " << "(" << i->a << "," << i->b << ")" << endl;
    }
    return 0;
}

输出

[ (3,8) (0,3) ]
--------------------------------
After erasing (3, 8)
[ (0,3) ]
--------------------------------
Searching for key (3,6)
Found : (0,3)

当比较对象是否相等时,std::set 使用比较函数(即 greater<node> 使用 node::operator>)而不是 node::operator==(如您所料)。

In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a).

对于node(3,6)node(0,3)operator> (node(3,6), node(0,3))operator> (node(0,3), node(3,6))returnfalse都是等价的