fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <functional>
  4. #include <algorithm>
  5.  
  6. template <typename T, typename cmp>
  7. void bubblesort(T ar[], int n, cmp compare_fn)
  8. {
  9. int swaps = 1;
  10. while (swaps)
  11. {
  12. swaps = 0;
  13. for (int i = 0; i < n - 1; i++)
  14. {
  15. if (!compare_fn(ar[i], ar[i + 1]))
  16. {
  17. std::swap(ar[i], ar[i + 1]);
  18. swaps = 1;
  19. }
  20. }
  21. }
  22. }
  23.  
  24. template <typename T>
  25. void bubblesort(T ar[], int n)
  26. {
  27. // call general version using <
  28. bubblesort(ar, n, std::less<T>());
  29. }
  30.  
  31. struct election
  32. {
  33. std::string party;
  34. std::string state;
  35. std::string pop;
  36. std::string reps;
  37. int ratio;
  38. };
  39.  
  40. using namespace std;
  41.  
  42. bool compare_pop_up(const election& e1, const election& e2)
  43. {
  44. return e1.pop > e2.pop; // if e1.pop comes before e2.pop, return true, else false
  45. }
  46.  
  47. int main()
  48. {
  49. election results[3];
  50. results[0].pop = "abc";
  51. results[1].pop = "123";
  52. results[2].pop = "def";
  53.  
  54. bubblesort<election>(results, 3, compare_pop_up);
  55.  
  56. for (int i = 0; i < 3; ++i)
  57. std::cout << results[i].pop << "\n";
  58. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
def
abc
123