fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. struct MyType {
  7. int a, b;
  8. };
  9.  
  10. template<class T, class U>
  11. class CompareByMember {
  12. U (T::*mem); // ugly syntax for member pointer of type U in class T
  13. public:
  14. CompareByMember(U (T::*mem)) : mem(mem) {}
  15. bool operator()(const T &a, const T &b) {
  16. return (a.*mem) < (b.*mem); // ugly syntax for member pointer access
  17. }
  18. };
  19.  
  20. template<class T, class U>
  21. CompareByMember<T,U> compareByMember(U (T::*mem)) {
  22. return CompareByMember<T,U>(mem);
  23. }
  24.  
  25. void print(std::vector<MyType> v) {
  26. for (MyType t : v)
  27. cout << t.a << ", " << t.b << endl;
  28. }
  29.  
  30. int main() {
  31. std::vector<MyType> v = {{1, 2}, {0, 3}, {2, 0}, {4, 1}, {3, 4}};
  32.  
  33. std::cout << "Sort by `a`:" << endl;
  34. std::sort(v.begin(), v.end(), compareByMember(&MyType::a));
  35. print(v);
  36.  
  37. std::cout << "Sort by `b`:" << endl;
  38. std::sort(v.begin(), v.end(), compareByMember(&MyType::b));
  39. print(v);
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Sort by `a`:
0, 3
1, 2
2, 0
3, 4
4, 1
Sort by `b`:
2, 0
4, 1
1, 2
0, 3
3, 4