ACM中,用重载函数会使解题更加方便,但是又需要像c++那样深入理解,遂简单总结了结构体中的重载运算符及const成员函数一些简单的用法.
闲言少叙,直接看代码:
/**
* 行有余力,则来刷题!
* 博客链接:http://blog.csdn.net/hurmishine
*
*/
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
const int maxn=0;
struct Node
{
int x,y;
Node()
{
x=0,y=0;
}
Node(int x,int y):x(x),y(y) {}
void setX(int x)
{
this->x=x;
}
//普通对象成员函数
void print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
//常对象成员函数
void print()const
{
cout<<"const"<<"("<<x<<","<<y<<")"<<endl;
}
//重载小于运算符,(set)
friend bool operator<(Node n1,Node n2)
{
//注意逻辑
if(n1.x==n2.x)
{
return n1.y<n2.y;
}
return n1.x<n2.x;
}
//重载<<运算符
friend ostream & operator << (ostream &os, Node node)
{
cout << "(" <<node.x<<","<<node.y<< ")";
return os;
}
};
int main()
{
Node n1;//默认构造函数
//cout<<n1<<endl;
Node n2(1,2);
//n2.print();
//n2.setX(2);
//n2.print();
//cout<<n2<<endl;
const Node n3(2,2);
//n3.print();
//cout<<n3<<endl;
//n3.setX(2);//ERROR
Node const n4(3,3);
//cout<<n4<<endl;
//n4.setX(2);//ERROR
//cout<<"-----------"<<endl;
set<Node>s;
s.insert(n1);
s.insert(n2);
s.insert(n3);
s.insert(n4);
s.insert(Node(4,2));
s.insert(Node{-1,1});//如果未写构造函数
set<Node>::iterator it;
for(it=s.begin(); it!=s.end(); it++)
{
cout<<*it<<endl;//重载了<<运算符
}
return 0;
}