struct point
{
int elem;
bool operator==(const point b) const
{
return this->elem == b.elem;
}
bool operator!=(const point b) const
{
return this->elem != b.elem;
}
bool operator<=(const point b) const
{
return this->elem <= b.elem;
}
bool operator<(const point b) const
{
return this->elem < b.elem;
}
bool operator>=(const point b) const
{
return this->elem >= b.elem;
}
bool operator>(const point b) const
{
return this->elem > b.elem;
}
}
重载运算符的格式如下:
bool operator 运算符 (const 结构体名称 b) const
{
return(什么时候这个运算符对结构体成立);//注意对此运算符使用this->元素名;
}
重点
bool operator<(const point s1) const
{
return this->v < s1.v;
}
所有的STL都会用到 < 小于号。
参考资料
https://blog.youkuaiyun.com/sunny1996/article/details/51242184
本文详细介绍了如何在C++中为自定义结构体`struct point`重载比较运算符,包括`==`, `!=`, `<=`, `<`, `>=`, 和 `>`。这些运算符的实现基于成员变量`elem`的比较,对于STL容器的使用至关重要,因为STL算法常常依赖于这些比较操作。
784

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



