sort 排序

默认的sort函数是按升序排
sort(a,a+n);

两个参数分别为待排序数组的首地址尾地址

 

STL中 sort 默认是字典序升序,如果我们要改变排序顺序,那么就可以使用 sort 的第三个参数:

 

如果希望a数组中的元素从大到小排列(或按照某一个规则进行排列),我们可以再为sort传入第三个参数——“排序方法”

sort(a, a + 5, greater<int>());

其中,greater表示“更大”的意思,<int>表示待排序的数组中的元素类型为int,整个这行代码表示让一个元素类型为整数的数组从大到小排序。

 

此时程序为:

#include <iostream>
#include <algorithm>
using namespace std;
int main() 
{
    int a[] = { 3, 4, 5, 2, 1 };
    sort(a, a + 5, greater<int>());
    return 0;
}

 

 


结构体中排序的用法

将 sort 的用法时,我们延申一下结构体:

结构体的构造函数

struct Student{
    string name;
    int score;
    Student(){}
    Student(string n, int s):name(n), score(s){}
};

除此之外,我们可以对结构体进行排序:

我们要达成的目的有两个:

1. 根据学生名字的字典序升序排序

2. 根据学生的成绩排序,若第一科成绩相同则看第二课成绩,依次类推

#include <iostream>
#include <string>
#include<algorithm>
using namespace std;

struct Student {
    string name;
    int score[4];
};

bool cmp_name(Student x,Student y){
	return x.name < y.name;
}

bool cmp_score(Student x, Student y){
    if(x.score[0] != y.score[0]){
        return x.score[0] > y.score[0];
    }
    if(x.score[1] != y.score[1]){
        return x.score[1] > y.score[1];
    }
    if(x.score[2] != y.score[2]){
        return x.score[2] > y.score[2];
    }
    return x.score[3] > y.score[3];
}

int main() {
    Student stu[3];
    for (int i = 0; i < 3; i++) {
        cin >> stu[i].name;
        for (int j = 0; j < 4; j++) {
            cin >> stu[i].score[j];
        }
    }
    sort(stu, stu + 3, cmp_name);
    for (int i = 0; i < 3; i++) {
        cout << stu[i].name << ":";
        for (int j = 0; j < 4; j++) {
            cout << stu[i].score[j] << " ";
        }
        cout<<endl;
    }
    sort(stu, stu + 3, cmp_score);
    for (int i = 0; i < 3; i++) {
        cout << stu[i].name << ":";
        for (int j = 0; j < 4; j++) {
            cout << stu[i].score[j] << " ";
        }
        cout<<endl;
    }
    
    return 0;
}

 

 

有一点特别要注意——那就是不能用 typedef 的同时去声明一个结构体数组

如下:

 

typedef struct Student{
	string name;
	int a, b, c, d;
}stu[50];

这样会报出  [Error] expected primary-expression before '[' token 的错误

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值