sort函数作为算法库内自带的排序算法,极大地减少了程序猿在编写排序所花的时间。要使用sort函数,只需引入头文件#include<algorithm>
函数写法为 sort(begin,end)
例如:
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
sort(a, a + 10);
cout << "after sort: ";
for (int i = 0; i < 10; i++){
cout << a[i] << ' ';
}
return 0;
}
输出结果为:
默认排序为升序排序,那么又怎样利用它进行降序排序呢?
1.为了满足不同情况排序的要求,sort函数在end后还可以加一个比较函数,即接受含三个参数的sort;
sort(begin,end,compare)
例如,为满足降序排序的需求
#include<algorithm>
#include<iostream>
using namespace std;
bool compare(int a, int b){
return a > b;
}
int main()
{
int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
sort(a, a + 10,compare);
cout << "after sort: ";
for (int i = 0; i < 10; i++){
cout << a[i] << ' ';
}
return 0;
}
输出结果为
2.对<进行运算符重载,因为sort主要是通过<来排序,在对类的排序中较为实用
3.利用functional标准库
其实c++标准库中已有现成可用的比较运算符,在头文件中引用include进来即可。
#include<functional>
其中functional提供了如下的基于模板的比较函数对象。
1.equal_to<type>:等于;
2.not_equal_to<type>:不等于;
3.greater<type>:大于;
4.greater_equal<type>:大于等于;
5.less<type>:小于;
6.less_equal<type:小于等于。
例如:
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;
int main()
{
int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
sort(a, a + 10,greater<int>());
cout << "after sort: ";
for (int i = 0; i < 10; i++){
cout << a[i] << ' ';
}
return 0;
}
就完成了降序排序