重载set的operator<()函数
struct A
{
int x;
int y;
int z;
/*
bool operator < (const A & other)const
{
return (x == other.x) ? y > other.y : x > other.x;
}
*/
}; // end of struct A
bool operator < (const A& i1, const A& i2)
{
return (i1.x == i2.x) ? i1.y > i2.y : i1.x > i2.x;
}
bool myfunction(int i, int j){return i > j;}
int main()
{
A a1;
a1.x = 0;
a1.y = 1;
a1.z = 2;
A a2;
a2.x = 0;
a2.y = 1;
a2.z = 2;
set<A> sa;
sa.insert(a1);
sa.insert(a2);
return 0;
}operator < 作为成员函数是得声明为const函数,表示不能修改A类对象的成员变量,保证被比较的两个对象内容不被修改。
operator< 作为独立函数声明时需要将两个对象都声明为const类型。
本文介绍了如何为自定义结构A重载小于运算符(operator<),使其能够用于std::set容器中。通过将operator<声明为非成员函数,并接受两个常量引用参数的方式,确保了比较过程中不会修改对象的状态。

508

被折叠的 条评论
为什么被折叠?



