fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. int main()
  6. {
  7. std::vector<int> container = {1,2,3,4,3,2,1,2,3,4};
  8.  
  9. // output
  10. std::cout << "Before: ";
  11. for(int n: container) std::cout << n << ' ';
  12. std::cout << '\n';
  13.  
  14. // erase every 2 using erase-remove
  15. int temp = 2;
  16. container.erase( std::remove(container.begin(), container.end(), temp),
  17. container.end() );
  18.  
  19. // output
  20. std::cout << "After erasing 2: ";
  21. for(int n: container) std::cout << n << ' ';
  22. std::cout << '\n';
  23.  
  24. // same thing (but slower) with a loop
  25. temp = 3;
  26. std::vector<int>::iterator itr1, itr2 = container.end();
  27. for (itr1=container.begin(); itr1 != itr2; )
  28. {
  29. if(*itr1==temp)
  30. itr1 = container.erase(itr1);
  31. else
  32. ++itr1;
  33. }
  34.  
  35. // output
  36. std::cout << "After erasing 3: ";
  37. for(int n: container) std::cout << n << ' ';
  38. std::cout << '\n';
  39. }
  40.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Before: 1 2 3 4 3 2 1 2 3 4 
After erasing 2: 1 3 4 3 1 3 4 
After erasing 3: 1 4 1 4