fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template<class RandomIt, class Consumer>
  5. void my_for_each(RandomIt comeco, RandomIt fim, Consumer faz_algo) {
  6. for (RandomIt it = comeco; it != fim; it++) {
  7. faz_algo(*it);
  8. }
  9. }
  10.  
  11. template<class RandomIt, class Comparador>
  12. void insertionsort(RandomIt comeco, RandomIt fim, Comparador cmp) {
  13. for (RandomIt it = comeco + 1; it != fim ; it++) {
  14. for (RandomIt it2 = it; it2 != comeco; it2--) {
  15. RandomIt prev = it2 - 1;
  16. if (cmp(*it2, *prev)) {
  17. auto e = *it2;
  18. *it2 = *prev;
  19. *prev = e;
  20. }
  21. }
  22. }
  23. }
  24.  
  25. template<class RandomIt, class Comparador>
  26. void bubblesort(RandomIt comeco, RandomIt fim, Comparador cmp) {
  27. for (RandomIt it = fim - 1; it != comeco ; it--) {
  28. for (RandomIt it2 = comeco; it2 != it; it2++) {
  29. RandomIt next = it2 + 1;
  30. if (!cmp(*it2, *next)) {
  31. auto e = *it2;
  32. *it2 = *next;
  33. *next = e;
  34. }
  35. }
  36. }
  37. }
  38.  
  39.  
  40. int main() {
  41. std::vector<int> v = {3, 3, 2, 1};
  42. insertionsort(v.begin(), v.end(), [](int a, int b) { return a < b; });
  43. my_for_each(v.begin(), v.end(), [](int a) { std::cout << a << std::endl; });
  44.  
  45. std::vector<int> v2 = {3, 3, 2, 1};
  46. bubblesort(v2.begin(), v2.end(), [](int a, int b) { return a < b; });
  47. my_for_each(v2.begin(), v2.end(), [](int a) { std::cout << a << std::endl; });
  48. return 0;
  49. }
Success #stdin #stdout 0s 5568KB
stdin
Standard input is empty
stdout
1
2
3
3
1
2
3
3