<span>重载运算符</span>
直接上代码解释三种吧。
#include<iostream> #include<cstring> #include<string> #include<cstdlib> #include<vector> #include<queue> #include<cmath> #include<map> #include<algorithm>
using namespace std; #define N 2021
#define mt(x) memset(x,0,sizeof x) typedef long long ll; void cn(ll x){cout<<x<<endl;} void cs(string x){cout<<x<<endl;} /* 结构体重载运算符 : + */
struct add { int a,b; add() { a=1; b=1; } add operator +(const add& y)const { add x; x.a+=y.a; x.b+=y.b; return x; } void pr() { cout<<a<<','<<b<<endl; } }; struct ii { int x,y; bool operator<(const ii& p)const { /* 首先一点,优先队列认为,从大到小排序 如下: return x<p.x; 意思是: 满足当前 x<p.x 则 当前队列元素<p,那么队列会把这个放在p后面 ,也即从大到小。 */
return x>p.x;//这是从小到大
} /* 另一种写法: friend bool operator <(ii a,ii b) { return a.x>b.x;//也是从小到大 } */
void pr() { cout<<x<<','<<y<<endl; } }; bool cmp(int x,int y) { return x<y; //0互换位置, 1不变。 //那么当这语句就是当x>=y时交换位置,也即从小到大
} void solve() { //1.结构体重载运算符
add a,b; a=a+b; a.pr(); puts("-----------------------\n"); //2.优先队列里结构体排序
priority_queue<ii>q; q.push({2,1}); q.push({1,1}); q.push({3,1}); while(!q.empty()) { ii now=q.top();q.pop(); now.pr(); } //另外,这也可以直接用于结构体大小比较
ii m,n; m.x=9;n.x=8; if(m<n)cs("m>n");//因为实际return m.x>n.x; 才有if(m<n)cs("m>n");
else cs("m<n"); puts("-----------------------\n"); //3.sort排序cmp
int numb[]={1,2,3,6,5,4}; printf("lenght==%d\n",sizeof(numb)/sizeof(int)); //cn(numb.length);JAVA语句 才能直接求数组长度,下面sort就直接写6了
sort(numb,numb+6,cmp); for(auto x:numb)cn(x); } int main() { ios::sync_with_stdio(false); cin.tie(0); solve(); return 0; }

查看11道真题和解析