【C++】结构体排序+sort(),cmp()参数写法口诀

题目:从键盘输入10个学生的姓名和成绩,请按字典序排列学生的姓名并输出(姓名和成绩对应关系保持不变)[SLOJ1334]
·结构体排序要加自定义比较函数cmp.此时
①sort()函数参数写法:sort(数组起始,数组结尾的下一位置,比较函数)
②自定义比较函数cmp()参数写法口诀:const类型引用名【重要】
在这里插入图片描述

//从键盘输入10个学生的姓名和成绩,
//请按字典序排列学生的姓名并输出(姓名和成绩对应关系保持不变)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int score;
};

//【参数写法】//const类型引用名 
bool cmp(const Student &a, const Student &b) {
    return a.name < b.name; //按什么排序 
}

//bool compareByName(Student a,Student b){ //别这样写,串长点运行可能不行 
//    return a.name < b.name;
//}

int main() {
    Student students[999]; 
	
    for (int i=0;i<=9;i++){
//        cin >> students[i].name; //也AC,已试 
		getline(cin,students[i].name); 
    }
	
    for (int i=0;i<=9;i++){ 
        cin >> students[i].score;
    }
	 
    //【意识】结构体排序要加自定义比较函数cmp  
	//【参数写法】sort(数组起始,数组结尾的下一位置,比较函数) 
	sort(students,students+10,cmp);
	
    for (int i=0;i<=9; i++) {
        cout <<  students[i].name << "," << students[i].score << endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值