通过代码及运行结果更有助于理解函数的使用,同时代码中注有详细的注释。
写在前面:函数reverse()和函数sort()都包含在头文件algorithm.h中
1、代码(附超级详细注释)
#include<iostream>
#include<algorithm>
using namespace std;
bool Comp(const int &a,const int &b)//sort函数默认是升序排序,可以通过重写排序比较函数进行降序排序
{
return a>b;
}
int main()
{
int str[10] = {2,5,1,9,0};
reverse(str,str+5); //翻转数组值
cout<<"翻转数组:";
for(int i=0; i<5; i++)
cout<<str[i]<<" ";
cout<<endl;
sort(str,str+5); //默认的升序排序
cout<<"升序:";
for(int i=0; i<5; i++)
cout<<str[i]<<" ";
cout<<endl;
sort(str,str+5,Comp); //重写之后的降序排序
cout<<"降序:";
for(int i=0; i<5; i++)
cout<<str[i]<<" ";
cout<<endl;
return 0;
}
2、运行结果
翻转数组:0 9 1 5 2
升序:0 1 2 5 9
降序:9 5 2 1 0