想起来自己天天排序排序,冒泡啊,二分查找啊,结果在STL中就自带了排序函数sort,qsort,总算把自己解脱了~
std::sort()函数的功能很强大,且可以对类,结构体等元素进行排序。C++sort参考手册
所以自己总结了一下,首先看sort函数见下表:参考csdn
函数名 | 功能描述 |
---|---|
sort | 对给定区间所有元素进行排序 |
stable_sort | 对给定区间所有元素进行稳定排序 |
partial_sort | 对给定区间所有元素部分排序 |
partial_sort_copy | 对给定区间复制并排序 |
nth_element | 找出给定区间的某个位置对应的元素 |
is_sorted | 判断一个区间是否已经排好序 |
partition | 使得符合某个条件的元素放在前面 |
stable_partition | 相对稳定的使得符合某个条件的元素放在前面 |
要使用此函数只需用#include <algorithm>
sort即可使用,语法描述为:
sort(begin,end),表示一个范围,例如:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
int a[10]={9,12,17,30,50,20,60,65,4,49};
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}
2)自己编写一个比较函数来实现,接着调用三个参数的sort:sort(begin,end,compare)就成了。对于list容器,这个方法也适用,把compare作为sort的参数就可以了,即:sort(compare).
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
bool compare(int a,int b)
{
return a<b; //默认升序排列,如果改为return a>b,则为降序
}
bool compare_decrease(int a,int b)
{
return a>b; //从大到小的排列
}
int main()
{
int a[10]={9,12,17,30,50,20,60,65,4,49};
sort(a,a+10);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
sort(a,a+10,compare_decrease);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}