c++ - set::find()无法与用户定义数据类型一起使用

标签 c++ stdset

当我搜索集合中不存在的键时,find()而不是将迭代器返回到末尾,而是将迭代器返回到另一个不等于键但在集合中存在的对象。
我不知道怎么了。
CODE

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))都返回false,因此它们被认为是等效的。

关于c++ - set::find()无法与用户定义数据类型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62607492/

相关文章:

c++ - 如何使用类对象上的指针在类中定义复制构造函数和 = 运算符重写?

c++ - 关于 union 和内存管理的问题

c++ - 如何打印 std::set of std::maps

c++ - 比较两组 std::weak_ptr

c++ - 如何将 std::find 与不是 std::less 的 < 运算符一起使用

c++ - 函数模板声明顺序影响可见性(有时)

c++ - 如何使用函数指针声明 lambda(不带 auto)?

c++ - 如何总结 std::set 的元素

C++:从模板化基类覆盖函数