fork(1) download
  1. #include <algorithm>
  2. #include <functional>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. struct TeamStats {
  7. std::string name;
  8. float yards_per_game;
  9. int total_points;
  10. };
  11.  
  12. using QuickSortPred = std::function<bool(const TeamStats&, const TeamStats&)>;
  13.  
  14. template<typename I>
  15. void quickSort(I begin, I end, QuickSortPred predicate)
  16. {
  17. /// NOTE: This is NOT a complete quicksort, it's just to demonstrate
  18. /// the usage of predicate.
  19.  
  20. std::sort(begin, end, predicate);
  21. }
  22.  
  23. int main() {
  24. std::vector<TeamStats> arr {
  25. { "Red", 100, 30, },
  26. { "Blue", 150, 10, },
  27. { "Green", 200, 20, },
  28. };
  29.  
  30. // approach one, store the lambda before hand
  31. auto sortByYards = [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  32. return lhs.yards_per_game < rhs.yards_per_game;
  33. };
  34. quickSort(arr.begin(), arr.end(), sortByYards);
  35. std::cout << "By yards:\n";
  36. for (auto& it : arr) {
  37. std::cout << it.yards_per_game << " " << it.name << "\n";
  38. }
  39.  
  40. // approach two, write the lambda inline.
  41. quickSort(arr.begin(), arr.end(), [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  42. return lhs.total_points < rhs.total_points;
  43. });
  44. std::cout << "By points:\n";
  45. for (auto& it : arr) {
  46. std::cout << it.total_points << " " << it.name << "\n";
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
By yards:
100 Red
150 Blue
200 Green
By points:
10 Blue
20 Green
30 Red