C++STL中的sort函数使用
C++STL中的sort函数使用
1.头文件
sort函数的头文件为< algorithm>
2.函数原型
void sort(start, end, method)
3.三个参数的含义
第一个参数:表示排序的起点位置,这个起点位置不一定是数组的0位置、或者vector的0位置,也可以是数组中间某个位置;
第二个参数:表示排序的终止位置,这个终止位置不一定是数组、vector等的最后一个元素,可以是倒数第二个、第三个等;
前两个参数指定了需要排序的区间,这个区间可以是全部数据的某个子集。
第三个参数:表示排序时使用的方法(升序或者降序),默认情况下该参数为空,表示按升序排序,也可自定义排序方法。
案例
1 对数组元素的排序
#include <algorithm>
#include <stdio.h>
bool cmp1(int a, int b)
{
return a < b;
}
bool cmp2(int a, int b)
{
return a > b;
}
int main()
{
int a[10] = {9,6,3,8,5,2,7,4,1,0};
for(int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
sort(a, a+10, cmp1);//对整个数组进行排序
sort(a, a+6);//对数组的前六个元素进行排序
sort(a+2, a+10);//对数组的第2个~第6个元素进行排序
for(i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
2 对结构体数组的排序
结构体定义如下:
struct node{
int a;
int b;
double c;
};
排序规则为:先按a升序排序,再按b降序排序,最后按c升序排序,案例如下(代码有误)。
#include <algorithm>
#include <stdio.h>
using namespace std;
struct node{
int a;
int b;
double c;
};
bool cmp(node A, node B)
{
if(A.a != B.a)
return A.a < B.a;//先按a值升序排列
if(A.b != B.b)
return A.b > B.b;//再按b值降序排列
return A.c > B.c;//最后按c降序排列
}
int main()
{
struct node arr[5] = {
{1,2,2.1},
{4,1,1.2},
{2,6,3.2},
{3,5,3.4},
{5,7,2.2}
};
for(int i = 0; i < 5; i++)
printf("%d %d %.1lf\n", arr[i].a, arr[i].b, arr[i].c);
printf("*****after sort*****\n");
sort(arr, arr+5, cmp);
for(i = 0; i < 5; i++)
printf("%d %d %.1lf\n", arr[i].a, arr[i].b, arr[i].c);
return 0;
}