头文件要求:#include <algorithm>
首先形式:sort(first_pointer,first_pointer+n,cmp);
前两个参数都是指针,最后一个cmp是比较的规则;cmp也可以是缺省的,因为这个时候默认的是按照升序排列来做的;
基础用法:就是对前n个元素进行升序排列:
扩展用法:编写sort(...)中的cmp;可以对数组进行降序排序,同时也可以对结构体排序;
①:对数组降序排序:
#include "stdafx.h"
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
bool cmp1(int a, int b)
{
return a > b;
}
int main()
{
int a[] = { 1,5,4,6,7,8,9,10 };
sort(a, a+8,cmp1);
for (int i = 0; i < 10; i++) {
cout << a[i] << endl;
}
return 0;
}
②对结构体中的某一个关键元素降序
#include "stdafx.h"
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
struct Student {
int id;
string name;
}stu[100];
bool cmp1(struct Student a,struct Student b)
{
return a.id > b.id;
}
int main()
{
stu[0].id = 123, stu[0].name = "asdasd";
stu[1].id = 124, stu[1].name = "qqqqqq";
stu[2].id = 125, stu[2].name = "wwwwww";
sort(stu,stu+3,cmp1);
for (int i = 0; i < 3; i++) {
cout << stu[i].id <<" "<<stu[i].name<<endl;
}
return 0;
}
③还可以直接使用STL的方法进行简单的降序和升序排序,对于结构体是不适合的,加上头文件#include <functional>;
例如:
sort(stu,stu+3,greater<struct Student>());//不可以对结构体排序
sort(a,a+3,greater<int>());//对int数组进行降序排序
sort(a,a+3,less<int>());//对int数组进行升序排序
④声明比较类:
struct Less
{
bool operator()(const Student& s1, const Student& s2)
{
return s1.id<s2.id; //升序排列
}
};
sort(sutVector.begin(),stuVector.end(),Less());