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. void quickSort(TeamStats* arr, size_t numTeams, QuickSortPred predicate)
  14. {
  15. /// NOTE: This is NOT a complete quicksort, it's just to demonstrate
  16. /// the usage of predicate.
  17.  
  18. for (size_t i = 0; i < numTeams - 1; ++i) {
  19. // before: if (arr[i] < arr[i+1])
  20. if (predicate(arr[i], arr[i+1]))
  21. std::swap(arr[i], arr[i+1]);
  22. }
  23. }
  24.  
  25.  
  26. int main() {
  27. TeamStats arr[] = {
  28. { "Red", 100, 30, },
  29. { "Blue", 150, 10, },
  30. { "Green", 200, 20, },
  31. };
  32.  
  33. // approach one, store the lambda before hand
  34. auto sortByYards = [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  35. return lhs.yards_per_game < rhs.yards_per_game;
  36. };
  37. quickSort(arr, 3, sortByYards);
  38.  
  39. // approach two, write the lambda inline.
  40. quickSort(arr, 3, [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  41. return lhs.total_points < rhs.total_points;
  42. });
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Standard output is empty