结构体sort排序
sort函数包含在头文件为 #include < algorithm > 中。
sort (first, last, cmp)
(1) first:是要排序的数组的起始地址。
(2) last:是结束的地址(最后一个数据的后一个数据的地址)
(3) cmp:排序方法,可以是从升序也可是降序。如果不写,则默认从小到大排序。
// 1.采用默认从小到大排序
int a[9] = {9,8,7,6,5,4,3,2,1};
sort(a, a+9);
for(int i = 0; i <= 8; i++) cout << a[i] << ' ';
// 2.自定义函数 从大到小排序
bool cmp(int a, int b){
return a>b;
}
sort(a, a+10, cmp);
// 3.结构体排序
struct node{
int x, y;
}a[n];
bool cmp(node a, node b){
if(a.x!=b.x) return a.x<b.x;
else return a.y<b.y; //若第一项相等则比较第二项
}
sort(a, a+n, cmp);
e.g.
67 89
90 56
90 99
例题:P1223 排队接水
#include<bits/stdc++.h>
const int N=1005;
using namespace std;
struct node{
int x;
int y;
}a[N];
bool cmp(node x,node y){
if(x.x!=y.x) return x.x<y.x;
else return x.y<y.y;
}
int main(){
int n;
cin>>n;
double sum=0;
for(int i=1;i<=n;i++){
int k;
cin>>k;
a[i].x=k;
a[i].y=i;
}
sort(a+1,a+1+n,cmp);
for(int i=1;i<=n;i++)
{
printf("%d ",a[i].y);
sum+=a[i].x*(n-i);
}
cout<<endl;
printf("%.2f",1.0*sum/n);
return 0;
}