構造簡單的二級排序比較器

初學,請看代碼


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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章