实例
struct pos{
int x;
int y;
// 重载小于符号
bool operator<(const pos& a) const{
if(x == a.x){
return y < a.y;
}else{
return x < a.x;
}
}
};
void test() {
set<pos> history;
pos cur = {0,0};
history.insert(cur);
}
1、为什么要重载小于符号?
答:STL中set的底层是红黑树,在进行插入或查找时需要进行大小判断。
2、为什么不重载==符号?
答:该实例中struct只包含两个int型变量,编译器会默认按照int类型的==
符号来进行整个struct是否相等的判断,如果struct中包含其他自定义的类
或者struct,则还是需要重载==符号的。
3、<函数不定义成const函数行吗?
答:不行,因为传入的是const变量,故只能调用const成员函数。