结构体:
结构体重载操作在结构体外实现
#include <iostream>
#include <set>
using namespace std;
typedef struct Node{
int val;
struct Node *next;
} LinkNode, *LinkList;
bool operator<(const LinkNode &a,const LinkNode &b){
return a.next < b.next;
}
int main(){
set<LinkNode> s;
LinkNode a,b,c;
a.val = 1;
b.val = 2;
c.val = 3;
a.next = &b;
b.next = &c;
c.next = NULL;
s.insert(a);
s.insert(b);
s.insert(c);
for (set<LinkNode>::iterator iter = s.begin(); iter != s.end();++iter){
cout << iter->val<< endl;
}
}
类:
重载操作在类内实现可以少写一个参数,因为自身的值可以直接使用this
获取
#include <iostream>
#include <set>
class Point {
public:
double x;
double y;
Point() = default;
Point(double x, double y) {
this->x = x;
this->y = y;
}
bool operator<(const Point& p) const{
if (this->x < p.x)return true;
if (this->x > p.x)return false;
if (this->y < p.y)return true;
return false;
}
};
int main()
{
std::set<Point> setData;
setData.insert(Point(1, 1));
setData.insert(Point(1, 2));
setData.insert(Point(2, 1));
setData.insert(Point(2, 2));
setData.insert(Point(2, 2));
//输出4是正确的
std::cout << setData.size() << std::endl;
return 0;
}