#include <iostream>
#include <algorithm>
using namespace std;
bool compare1(int x,int y) //升序
{
return x<y;
}
bool compare2(int x,int y) //降序
{
return x>y;
}
void main()
{
int a[5]={3,2,4,5,1};
sort(a,a+5,compare1);
for(int i=0;i<5;i++)
cout<<a[i]<<"\t";
cout<<endl;
sort(a,a+5,compare2);
for( i=0;i<5;i++)
cout<<a[i]<<"\t";
cout<<endl;
}
原型:sort(指针1,指针2,bool (*fun)(class a,class b));第一个参数是要排序的区间首地址,第二个参数是区间尾地址的下一地址bool cmp(int a,int b) { return a>b; } 排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类 string 。 如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数——比较函数。比较函数是一个自己定义的函数,返回值是 bool 型,它规定了什么样的关系才是“小于”。想把刚才的整数数组按降序排列,可以先定义一个比较函数 cmp bool cmp(int a,int b) { return a>b; }