重写操作符

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

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

int main(){
   vector<Student> vec;
   vec.emplace_back("zhangsan", 93);
   vec.emplace_back("lisi", 91);
   vec.emplace_back("wanger", 95);
   vec.emplace_back("liuqi", 90);
   vec.emplace_back("mawu", 92);
   sort(vec.begin(), vec.end());
   for (int i = 0; i<vec.size(); i++){
      cout << vec[i] <<",";
   }
   cout << endl;
   return 0;
}

 

posted @ 2022-10-20 22:09  放弃吧  阅读(15)  评论(0编辑  收藏  举报