algorithm中已经帮我们写好了代码,直接使用即可,别忘了把这个头文件写上。
下面展示对数组内数字由大到小排序
代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
bool compare(int a,int b)
{
return a>b;//大于号是从大到小,小于号是从小到大
}
int main()
{
int a[10]={9,6,3,8,5,2,7,4,1,0};//待排序数组
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a,a+10,compare);//在这里就不需要对complare函数传入参数了,
//这是规则
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
输出:9 8 7 6 5 4 3 2 1 0
0 条评论