1. head file :
# include <algorithm>
2. 使用:
对数组a进行排序:
# include <iostream>
# include <algorithm>
using namespace std;
int main()
{
int a[5] = {5, 8, 7, 9, 2};
sort(a, a+5);
return 0;
}
此段代码表示对数组a,下标[0,5)(左闭右开区间,即a[0]、a[1]、a[2]、a[3]、a[4]进行排序,默认升序排序,并改变原数组。排序后,a数组为:2 5 7 8 9。
当然也可以自定义排序规则,并且对结构体数组进行排序。
自定义从大到小排序的代码:
//自定义cmp函数
# include <iostream>
# include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
.
//main 函数中,sort函数写法:
sort(a, a+5, cmp);
对结构体进行升序排序
# include <iostream>
# include <algorithm>
using namespace std;
struct ss
{
int x, y;
};
bool cmp(ss s1, ss s2) //对结构体ss,先按x升序排列,若x相同,则按y升序排列
{
if(s1.x == s2.x)
{
return s1.y < s2.y;
}
return s1.x < s2.x;
}
int main()
{
ss s[5];
//初始化过程略
sort(s, s+5, cmp);
//后续操作
}
从以上可以看出,sort 函数前两个参数是指针类型,即STL容器中的迭代器(iterator)类型,故而对于vector等容器的排序需要用到容器的专用函数
对STL容器排序,以vector为例
# include <vector>
# include <iostream>
# include <algorithm>
using namespace std;
int main()
{
vector<int> v;
//要用到的函数:
v.begin(); //指向开头
v.end(); //指向结尾的后一个位置
//sort实现
sort(v.begin(), v.end(), cmp);
}