结构体
结构体类型的声明格式如下:
struct 类型名{
数据类型1 成员名1;
数据类型2 成员名2;
…
} ;
struct 类型名{
数据类型1 成员名1;
数据类型2 成员名2;
…
} 变量名;
结构体变量具有以下特点:
(1)可以对结构体变量的整体进行操作。
例如:swap(a[i],a[j])
(2)可以对结构体变量的成员进行操作。
引用结构体变量中成员的格式为:
结构体变量名. 成员名
(3)结构体变量的初始化方法与数组类似。
万能头文件:bits/stdc++.h
1、运算符重载:
常用于解决结构体或自定义数据类型的加法、减法等特殊含义的运算。运算符重载的一般格式为:
类型名 operator 运算符 (const 类型名 变量)const{
…
}
例如:
// 声明一个结构体类型 worktime 记录学生完成作业的时间
struct worktime{
int hr,minut,sec; // hr,minut,sec 分别代表时分秒
};
worktime operator +(const worktime x)const{
// 对 + 进行重新定义;
worktime tmp;
tmp.sec = (sec + x.sec) % 60;
tmp.minut = (minut + x.minut + (sec + x.sec) / 60) % 60;
tmp.hr = hr + x.hr + (minut + x.minut + (sec + x.sec) / 60) / 60;
return tmp;
}
2、成员函数
在 C++ 中,允许在结构中定义函数,该函数称为“成员函数”。描述形式如下:
struct 结构名 {
数据成员
成员函数
…
};
sort()排序函数
使用sort函数必须用头文件#include < algorithm>和using namespace std;
Sort函数有三个参数:
(1)第一个是要排序的结构体(数组)的起始地址。
(2)第二个是结束的地址(最后一位要排序的地址的下一地 址)
3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。
#include
#include
using namespace std;
bool cmp( const int a,const int b)
{
return a>b;
}
int main()
{
int a[5] = {1,2,4,3,5};
sort(a,a + 5);//升序
for(int i = 0;i < 5; i++)
cout<<" “<<a[i];
cout<<endl;
sort(a,a + 5,cmp);//降序
for(int i = 0;i < 5; i++)
cout<<” "<<a[i];
cout<<endl;
return 0;
}