结构体之构造函数和重载运算符(包含对sort函数的使用)
1.构造函数写法
- 用this指针
struct treeNode{
char val;//数据域
treeNode* lchild;//左指针
treeNode* rchild;//右指针
treeNode(char val,treeNode* lchild,treeNode* rchild){
//构造函数必须和结构体类型命名一致
//注意此构造函数后面没有分号
this->val=val;
this->lchild=lchild;
this->rchild=rchild;
}
//当然传入参数也可以和结构体成员变量不重名,就不需要this指针了
};
- 简便写法
struct Point{
int x;
int y;
Point(int x_,int y_):x(x_),y(y_){}//要注意冒号和分号位置
};
2.重载运算符和sort函数
- 不重载写一个cmp函数
#include<bits/stdc++.h>
using namespace std;
struct Point{
int x;
int y;
Point(int x,int y):x(x),y(y){}
};
bool cmp(Point a,Point b){
if(a.x==b.x) return a.y<b.y//当x坐标的值相同是按y升序排列
return a.x<b.x//先按照x的值升序排列
//把小于号变成大于号就是降序排列
}
int main(){
vector<Point> point;
Point point1(3,27);
Point point2(11,21);
Point point3(6,20);
point.push_back(point1);
point.push_back(point2);
point.push_back(point3);
//此时使用sort函数
sort(point.begin(),point.end(),cmp);//首迭代器,末迭代器,cmp函数
int size=point.size();
for(int i=0;i<size;i++){
cout<<point[i].x<<" "<<point[i].y<<endl;
}
return 0;
}
关于sort函数,它的排序并不稳定,即大小相同的元素排序之后相对顺序可能发生变化,此时可以使用stable_sort函数,此处不过多介绍,sort函数默认为升序排列,降序排列可以写cmp函数,也可以使用一下语句
sort(v.begin(),v.end(),greater<int>());
//注意里面的类型可以不为int,也可以是double之类;
- 重载运算符
struct Point
{
int x;
int y;
bool operator < (const Point &other) const//重载小于号,other名可以变
{
if(x==other.x){
return y<other.y;//升序
}
return x<other.x;
}
};
//此时写sort函数就不用传入cmp函数了,直接传入首迭代器和末迭代器即可
以上是结构体和sort函数的一些常见用法,还有一些具体的解释不是很到位,以其其他写法我没有枚举,可以看其他博客继续学习,欢迎批评与指正!