Bootstrap

【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;
}

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;