当前位置: 代码迷 >> 综合 >> C++ class对象 使用 sort 排序练习
  详细解决方案

C++ class对象 使用 sort 排序练习

热度:68   发布时间:2023-10-24 01:51:38.0

在这道题中,我们要读入若干个人的名字和考试成绩,然后你要对其进行 从小到大 排序之后再依次输出这些人名和成绩,并且输出它们的个数。

输入和输出的具体格式可以参照输入样例。排序规则为优先按照分数排序,如果分数相同的话则按照姓名的字典序排序。

输入格式:一共若干个人的姓名和成绩,每条占一行,格式为人名 分数

 输出格式:将所有成绩条目排序之后输出,每条占一行,格式与输入完全相同,然后在最后一行输出数字的总个数。

 样例输入:

Alice 89
Bob 100
Selina 92
Dick 85
Fairy 85

 样例输出:

Dick 85
Fairy 85
Alice 89
Selina 92
Bob 100
5

 代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
using std::sort;class student{public:student(const string& inname, const int& insource): name(inname), source(insource){}string getName() const{return this->name;}int getSource() const{return this->source;}private:string name;int source;
};bool cmp(const student &a, const student &b){if (a.getSource() > b.getSource()){return false;}else if (a.getSource() < b.getSource()){return true;}else{//如果等于if(a.getName() < b.getName()){return true;}else{return false;}}
};int main(){vector<student> s;int input;string name;while(cin >> name >> input){s.push_back(student(name,input));}sort(s.begin(), s.end(), cmp);for(int i = 0; i < s.size(); i++){cout << s[i].getName() << " " << s[i].getSource() << endl;if( i == s.size() - 1){cout << s.size() << endl;}}
}

 

  相关解决方案