fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. template <typename Comparer>
  6. struct InvComparer
  7. {
  8. public:
  9. explicit InvComparer(Comparer comparer) : comp(comparer) {}
  10. template <typename T1, typename T2>
  11. constexpr bool operator() (const T1& lhs, const T2& rhs) const { return comp(rhs, lhs); };
  12. private:
  13. Comparer comp;
  14. };
  15.  
  16. int main()
  17. {
  18. std::vector<int> v = {16, 15, 4, 8, 42, 23};
  19.  
  20. auto comp = std::less<>{};
  21. std::sort(v.begin(), v.end(), comp);
  22.  
  23. for (const auto e : v) { std::cout << " " << e; }
  24. std::cout << std::endl;
  25.  
  26. InvComparer<decltype(comp)> invComp{comp};
  27. std::sort(v.begin(), v.end(), invComp);
  28. for (const auto e : v) { std::cout << " " << e; }
  29. std::cout << std::endl;
  30.  
  31. // check that inverse of < is > and not >=
  32. std::cout << std::boolalpha << invComp(42, 42) << std::endl;
  33. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
 4 8 15 16 23 42
 42 23 16 15 8 4
false