fork download
  1. #include<algorithm>
  2. #include<iostream>
  3. #include<iomanip>
  4. #include<vector>
  5. #include<string>
  6.  
  7. using namespace std;
  8.  
  9. struct Account
  10. {
  11. string Name;
  12. int Position;
  13. int Score;
  14. };
  15.  
  16. //overloading bool operator sorting by position
  17. bool operator<(const Account& lhs, const Account& rhs)
  18. {
  19. return lhs.Position < rhs.Position;
  20. }
  21.  
  22. //comparing using predicate
  23. bool compare_by_score(const Account& lhs, const Account& rhs)
  24. {
  25. return lhs.Score < rhs.Score;
  26. }
  27.  
  28.  
  29. void print_account(const Account& acc)
  30. {
  31. std::cout << std::setw(6) << acc.Name << " holds " << acc.Position <<
  32. " position with score " << acc.Score << '\n';
  33. }
  34.  
  35. int main()
  36. {
  37. std::vector<Account> data {{"John", 2, 56}, {"Sarah", 3, 12}, {"Rick", 5, 3},
  38. {"Miles", 1, 41}, {"Jane", 4, 60} };
  39. for(const auto& acc: data)
  40. print_account(acc);
  41.  
  42. std::cout << "\nDefault sorting, sorts using operator <:\n";
  43. std::sort(data.begin(), data.end());
  44. for(const auto& acc: data)
  45. print_account(acc);
  46.  
  47. std::cout << "\nSorting using predicate:\n";
  48. std::sort(data.begin(), data.end(), compare_by_score);
  49. for(const auto& acc: data)
  50. print_account(acc);
  51.  
  52. std::cout << "\nSorting using lambdas:\n";
  53. std::sort(data.begin(), data.end(),
  54. [](const Account& lhs, const Account& rhs){return lhs.Name < rhs.Name;});
  55. for(const auto& acc: data)
  56. print_account(acc);
  57. }
Success #stdin #stdout 0s 3244KB
stdin
Standard input is empty
stdout
  John holds 2 position with score 56
 Sarah holds 3 position with score 12
  Rick holds 5 position with score 3
 Miles holds 1 position with score 41
  Jane holds 4 position with score 60

Default sorting, sorts using operator <:
 Miles holds 1 position with score 41
  John holds 2 position with score 56
 Sarah holds 3 position with score 12
  Jane holds 4 position with score 60
  Rick holds 5 position with score 3

Sorting using predicate:
  Rick holds 5 position with score 3
 Sarah holds 3 position with score 12
 Miles holds 1 position with score 41
  John holds 2 position with score 56
  Jane holds 4 position with score 60

Sorting using lambdas:
  Jane holds 4 position with score 60
  John holds 2 position with score 56
 Miles holds 1 position with score 41
  Rick holds 5 position with score 3
 Sarah holds 3 position with score 12