当我搜索集合中不存在的键时,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
andb
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/