C++ 类对象排序

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

class Stu{
protected:
	string name;
	int score;
public:
	Stu(string name, int score){
		this->name = name;
		this->score = score;
	}
	bool operator < (const Stu &s){
		return this->score < s.score;
	}
	friend ostream& operator << (ostream& o, const Stu &s);
};

ostream& operator << (ostream& o, const Stu &s){
	o << "[" << s.name << ", " << s.score << "]";
	return o;
}

int main(){
//	int array[11] = {11, 222, 3, 44, 5, 666, -100, 0, 999, -123, 1};
//	sort(array, array + 11, greater<int>());
//	sort(array, array + 11, cmp);
//	vector<int> v = {11, 222, 3, 44, 5, 666, -100, 0, 999, -123, 1};
	vector<Stu> v;
	v.emplace_back("zhangsan", 95);
	v.emplace_back("li", 91);
	v.emplace_back("wangwu", 99);
	v.emplace_back("zhaoliu", 90);
	v.emplace_back("AAAA", 96);
//	sort(v.begin(), v.end());
//	sort(v.begin(), v.end(), greater<int>());
	sort(v.begin(), v.end());
	for(auto x : v) cout << x << ",";
	cout << endl;
	return 0;
}
发布了135 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/LightInDarkness/article/details/104552595