sort-函数

sort-对给定区间所有元素进行排序

一、两个参数的sort(begin,end),begin,end表示一个范围,默认为升序。需要引用#include <algorithm>

示例如下:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
int a[10]= {21,4,10,78,9,31,48,90,19,80},i;
for(i=0; i<10; i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a,a+10);
for(i=0; i<10; i++)
cout<<a[i]<<" ";
return 0;
}

二、一种更为通用的方法是自己编写一个比较函数compare来实现,接着调用三个参数的sort(begin,end,compare)

示例如下:

#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int num1,int num2)
{
return num1>num2; //降序排列

}

int main()
{
int a[10]= {21,4,10,78,9,31,48,90,19,80},i;
for(i=0; i<10; i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a,a+10,compare);
for(i=0; i<10; i++)
cout<<a[i]<<" ";
return 0;
}

原文地址:https://www.cnblogs.com/Xbert/p/5159499.html