sort函数
中文名:Sort函数
头文件:#include using namespace std;
用途:对给定区间所有元素进行排序
所属范畴:C++
Sort函数有三个参数:
(1)第一个是要排序的结构体(数组)的起始地址。
(2)第二个是结束的地址(最后一位要排序的地址的下一地址)
(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。
//两个参数 默认从小到大排列
#include<stdio.h>
#include<algorithm>
using namespace std;
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);
for(int i=0; i<10; i++)
printf("%d",a[i]);
printf("\n");
return 0;
}
//三个参数 用函数控制从小到大还是从大到小排列
#include<stdio.h>
#include<algorithm>
using namespace std;
bool compare(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,compare);//在这里就不需要对compare函数传入参数了,
//这是规则
for(int i=0; i<10; i++)
printf("%d",a[i]);
printf("\n");
return 0;
}
//看http://nyoj.top/第八题《一种排序》 下面的是那道题的简化 使用结构体排序
// 改一下bool里的小于号观看现象有助于理解
#include <stdio.h>
#include <algorithm>
using namespace std;
struct stu
{
int a;
int b;
int c;
} rect[7]= {{1,1,1},
{1,1,2},
{1,2,1},
{1,2,2},
{2,1,1},
{2,1,2},
{2,2,1}};
bool cmp(stu x,stu y)//return中">"从大到小排列 "<"从小到大排列
{
if(x.a==y.a)
{
if(x.b==y.b)
return x.c<y.c;//每组第三个数怎么排序
return x.b<y.b;//每组第二个数怎么排序
}
return x.a<y.a;//每组第一个数怎么排序
}
int main()
{
sort(rect, rect + 7, cmp);
for (int i = 0; i<7; i++)
{
printf("%d %d %d\n",rect[i].a,rect[i].b,rect[i].c);
}
return 0;
}