fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iterator>
  5.  
  6. template <typename iter_type>
  7. void print(iter_type beg, iter_type end)
  8. {
  9. std::cout << "{ ";
  10. while (beg != end)
  11. std::cout << *beg++ << ' ';
  12. std::cout << "}\n";
  13. }
  14.  
  15. template <typename container_type>
  16. void print(const container_type& container)
  17. {
  18. print(std::begin(container), std::end(container));
  19. }
  20.  
  21. void remove_copies_of_front_with_remove_erase_idiom(std::vector<int>& v)
  22. {
  23. v.erase(std::remove(v.begin()+1, v.end(), v.front()), v.end());
  24. }
  25.  
  26. void remove_copies_of_front_with_while_loop(std::vector<int>& v)
  27. {
  28. unsigned i = 1;
  29. while (i < v.size())
  30. {
  31. if (v[i] == v[0])
  32. v.erase(v.begin() + i);
  33. else
  34. ++i;
  35. }
  36. }
  37.  
  38. int main()
  39. {
  40. using vec_t = std::vector<int>;
  41.  
  42. vec_t original = { 1, 1, 1, 2, 1, 3, 1, 1, 4, 1, 1, 5 };
  43. vec_t expected_result = { 1, 2, 3, 4, 5 };
  44.  
  45. auto a = original;
  46. std::cout << "Before remove-erase idiom applied\n\ta: ";
  47. print(a);
  48.  
  49. remove_copies_of_front_with_remove_erase_idiom(a);
  50. std::cout << "\nAfter removal\n\ta: ";
  51. print(a);
  52.  
  53. if (a == expected_result)
  54. std::cout << "Success!\n\n";
  55. else
  56. std::cout << "Failure!\n\n";
  57.  
  58. auto b = original;
  59. std::cout << "Before while removal\n\tb: ";
  60. print(b);
  61.  
  62. remove_copies_of_front_with_while_loop(b);
  63. std::cout << "\nAfter removal\n\tb: ";
  64. print(b);
  65.  
  66. if (b == expected_result)
  67. std::cout << "Success!\n\n";
  68. else
  69. std::cout << "Failure!\n\n";
  70. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Before remove-erase idiom applied
	a: { 1 1 1 2 1 3 1 1 4 1 1 5 }

After removal
	a: { 1 2 3 4 5 }
Success!

Before while removal
	b: { 1 1 1 2 1 3 1 1 4 1 1 5 }

After removal
	b: { 1 2 3 4 5 }
Success!