fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <initializer_list>
  5. #include <cassert>
  6. using namespace std;
  7.  
  8. template<typename T>
  9. std::ostream& operator<<(std::ostream& out, const std::vector<T>& v){
  10. for(const auto& el : v){
  11. out << el << '\n';
  12. }
  13. return out;
  14. }
  15.  
  16. class A {
  17. int a;
  18. int b;
  19. public:
  20. A(std::initializer_list<int> l){
  21. assert(l.size() == 2);
  22. auto i = l.begin();
  23. a = *i;
  24. ++i;
  25. b = *i;
  26. }
  27.  
  28. friend std::ostream& operator<<(std::ostream& stream, const A& e){
  29. return stream << e.a << ' ' << e.b;
  30. }
  31.  
  32. static bool compareViaA(const A& lhs, const A& rhs){
  33. return rhs.a > lhs.a;
  34. }
  35.  
  36. static bool compareViaB(const A& lhs, const A& rhs){
  37. return rhs.b > lhs.b;
  38. }
  39. };
  40.  
  41. int main() {
  42. std::vector<A> v {{2,3}, {3,2}, {1,4}, {4,1}};
  43. //sort(v.begin(), v.end(), [](const A& a, const A& b){return a.a > b.a;}) // fails because of privacy violation
  44. sort(v.begin(), v.end(), A::compareViaA);
  45. std::cout << v << '\n';
  46. sort(v.begin(), v.end(), A::compareViaB);
  47. std::cout << v << '\n';
  48. return 0;
  49. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
1 4
2 3
3 2
4 1

4 1
3 2
2 3
1 4