初学,请看代码
#include <iostream> #include <string> #include <algorithm> #include <sstream> using namespace std; class Student { public: int grade; string name; }; //构造二级排序比较器 bool lessCmp(Student &a, Student &b) { if (a.grade < b.grade) { return true; } else if (a.grade == b.grade) { if (a.name < b.name) return true; else return false; } return false; } int main() { const int n = 50; Student *stu=new Student[n]; //初始化,让id相同时name存在不同的情况 for (int i = 0; i < n; i++) { stringstream iss; string temp; iss << i / 10; iss >> temp; cout << temp << endl; stu[i].grade = i % 7; stu[i].name = temp; } //排序 sort(stu, stu + n, lessCmp); //输出 for (int i = 0; i < n; i++) { cout << "id=" << stu[i].grade << " name=" << stu[i].name << endl; } return 0; }
