1. sort函数
int a[10] = {9,6,3,8,5,2,7,4,1,0};
sort(a,a+10);
以上默认是从小到大排序的。参数分别是数组的首地址、首地址+数组长度。
如果想按自己的意愿排序,可以重写complare函数,如下
#include<iostream>
#include<algorithm>
using namespace std;
bool complare(int a,int b) {
return a>b;
}
int main() {
int a[10]={9,6,3,8,5,2,7,4,1,0};
sort(a,a+10,complare); //在这里就不需要对complare函数传入参数了
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
你可以模仿上面的做法自己写一个结构体排序。
2. swap函数
交换两个对象的值,用法如下:
int a=1, b=2;
swap(a,b);
a与b两个数值交换
3. 最大最小操作
int a=1, b=2;
cout<<max(a,b)<<' ';
cout<<min(a,b);