sort对结构体排序(程序设计与算法(一))

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct student
{
	string name;
	int ID;
	double gpa;
}a[] = { {"Jack",112,3.4} ,{"Mary",102,3.8},{"Pery",117,3.9},{"Ala",333,3.8},{"Zera",101,4.0} };
struct STU  
{
	bool operator()(const student & a1, const student & a2)
	{
		if (a1.gpa != a2.gpa)
			return a1.gpa > a2.gpa;
		else 
		    return a1.name < a2.name
				
	}
};
int main()
{
	int n = sizeof(a) / sizeof(student);
	sort(a, a + n, STU());
	for (auto r : a)
		cout << r.gpa << ends << r.name << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/87093568