前言:结构体是比较常用的数据结构,构造函数有多种方法。 另外,结构体的比较常为基于多关键字的比较,我们可以通过内嵌方式和外部定义两种方式实现结构体的多关键字比较
一,结构体申明以及操作符重载:
struct Node{
int a;
int b;
Node() :a(), b(){}//构造函数1
Node(int _a, int _b) :a(_a),b(_b){}//构造函数2
void init(int _a,int _b){//构造函数3
this->a=_a;
this->b=_b;
}
//重载操作符,多用于结构体多关键字比较;
bool operator < (const Node& N ) const{
if(a==N.a)
return b<N.b;
else return a<N.a;
};
}q[10];
二,外置比较函数传参方法:
还有一种方法是申明cmp函数传参到sort()内
不过这种方法相比于结构体内嵌比较函数而言速度慢
bool cmp(Node x,Node y){
if(x.a==y.a)
return x.b<y.b;
else return x.a<y.a;
}
三,测试代码:
#include <bits/stdc++.h>
using namespace std;
struct Node{
int a;
int b;
Node() :a(), b(){}//构造函数1
Node(int _a, int _b) :a(_a),b(_b){}//构造函数2
void init(int _a,int _b){//构造函数3
this->a=_a;
this->b=_b;
}
//重载操作符,多用于结构体多关键字比较;
bool operator < (const Node& N ) const{
if(a==N.a)
return b<N.b;
else return a<N.a;
};
}q[10];
bool cmp(Node x,Node y){
if(x.a==y.a)
return x.b<y.b;
else return x.a<y.a;
}
int main(){
for(int i=0; i<10; i++){
int a=rand();
int b=rand();
q[i]=Node(a,b);
printf("%d %d\n",q[i].a,q[i].b);
}
printf("\n");
sort(q,q+10,cmp);//这里可以不用cmp
for(int i=0; i<10; i++){
printf("%d %d\n",q[i].a,q[i].b);
}
return 0;
}
输出:
41 18467
6334 26500
19169 15724
11478 29358
26962 24464
5705 28145
23281 16827
9961 491
2995 11942
4827 5436
41 18467
2995 11942
4827 5436
5705 28145
6334 26500
9961 491
11478 29358
19169 15724
23281 16827
26962 24464