1. 程式人生 > >按學生成績進行升序排列

按學生成績進行升序排列

有兩種方法,一是過載Student類中的“<”運算子。二是自己定義一個普通的全域性比較函式。

一、過載Student類中的“<”運算子

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class Student
{
public:
	int ID;
	string name;
	int grade;
	Student(int ID,string name,int grade)
	{
		this->ID = ID; this->name = name; this->grade = grade;
	}
	bool operator<(const Student &s) const
	{
		return grade<s.grade;
	}
};
int main()
{
	Student s1(101,"張三",91); Student s2(102,"李四",85);
	Student s3(103,"王五",60); Student s4(104,"趙六",72);
	vector<Student> v;
	v.push_back(s1); v.push_back(s2);
	v.push_back(s3); v.push_back(s4);
	sort(v.begin(),v.end());
	//也可以使用
//sort(v.begin(),v.end(),less<Student>());
	cout<<"升序排序結果:"<<endl;
	cout<<"學號\t"<<"姓名\t"<<"成績"<<endl;
	vector<Student>::iterator iter=v.begin();
	while(iter!=v.end())
	{
		cout<<iter->ID<<"\t"<<iter->name<<"\t"<<iter->grade<<endl;;
		iter++;
	}
	cout<<endl;
	return 0;   
}

輸出結果如下所示:

二、使用普通的全域性比較函式

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class Student
{
public:
	int ID;
	string name;
	int grade;
	Student(int ID,string name,int grade)
	{
		this->ID = ID; this->name = name; this->grade = grade;
	}
};
//普通的全域性比較函式
bool mygreater(Student &s1, Student &s2)
{
	return s1.grade<s2.grade;
}
int main()
{
	Student s1(101,"張三",91); Student s2(102,"李四",85);
	Student s3(103,"王五",60); Student s4(104,"趙六",72);
	vector<Student> v;
	v.push_back(s1); v.push_back(s2);
	v.push_back(s3); v.push_back(s4);
	sort(v.begin(),v.end(),mygreater); //更改sort函式,去掉Student類中的bool operator<(const Student &s)
cout<<"升序排序結果:"<<endl; cout<<"學號\t"<<"姓名\t"<<"成績"<<endl; vector<Student>::iterator iter=v.begin(); while(iter!=v.end()) { cout<<iter->ID<<"\t"<<iter->name<<"\t"<<iter->grade<<endl;; iter++; } cout<<endl; return 0; }

輸出結果與上圖一致。