主页 > IT业界  > 

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

【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; }
标签:

【C++】结构体排序+sort(),cmp()参数写法口诀由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“【C++】结构体排序+sort(),cmp()参数写法口诀