Advertisement
zhangsongcui

Comparing Function

Jun 19th, 2011
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <functional>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <string>
  5. #include <list>
  6.  
  7. struct Student
  8. {
  9.     friend std::istream& operator >>(std::istream& input, Student& stu)
  10.     {
  11.         return input >> stu.number >> stu.name >> stu.chinese_score >> stu.math_score >> stu.english_score;
  12.     }
  13.  
  14.     friend std::ostream& operator <<(std::ostream& output, const Student& stu)
  15.     {
  16.         output << std::setw(15) << stu.number
  17.                << std::setw(15) << stu.name
  18.                << std::setw(5)  << stu.chinese_score
  19.                << std::setw(5)  << stu.math_score
  20.                << std::setw(5)  << stu.english_score;
  21.         return output;
  22.     }
  23.  
  24.     std::string number;
  25.     std::string name;
  26.     int chinese_score;
  27.     int math_score;
  28.     int english_score;
  29. };
  30.  
  31. template <typename T, typename Fn = std::less<T> >
  32. struct Compare: std::binary_function<Student, Student, bool>
  33. {
  34.     Compare(const T Student::*_p, Fn _fn=Fn()): p(_p), fn(_fn) {}
  35.     bool operator ()(const Student& a, const Student& b) const
  36.     {
  37.         return fn(a.*p, b.*p);
  38.     }
  39.  
  40. private:
  41.     const T Student::*p;
  42.     Fn fn;
  43. };
  44.  
  45. int main()
  46. {
  47.     std::list<Student> student_list;
  48.     student_list.sort(Compare<std::string>(&Student::number));  //std::less<std::string>
  49.     student_list.sort(Compare<int, std::greater<int> >(&Student::chinese_score));
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement