fork 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. int main() {
  13. std::vector<TeamStats> arr {
  14. { "Red", 100, 30, },
  15. { "Blue", 150, 10, },
  16. { "Green", 200, 20, },
  17. };
  18.  
  19. // approach one, store the lambda before hand
  20. auto sortByYards = [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  21. return lhs.yards_per_game < rhs.yards_per_game;
  22. };
  23. std::sort(arr.begin(), arr.end(), sortByYards);
  24. std::cout << "By yards:\n";
  25. for (auto& it : arr) {
  26. std::cout << it.yards_per_game << " " << it.name << "\n";
  27. }
  28.  
  29. // approach two, write the lambda inline.
  30. std::sort(arr.begin(), arr.end(), [](const TeamStats& lhs, const TeamStats& rhs) -> bool {
  31. return lhs.total_points < rhs.total_points;
  32. });
  33. std::cout << "By points:\n";
  34. for (auto& it : arr) {
  35. std::cout << it.total_points << " " << it.name << "\n";
  36. }
  37.  
  38. return 0;
  39. }
Success #stdin #stdout 0s 3420KB
stdin
Standard input is empty
stdout
By yards:
100 Red
150 Blue
200 Green
By points:
10 Blue
20 Green
30 Red