fork download
  1. // Use g++ -std=c++11 or clang++ -std=c++11 to compile.
  2.  
  3. #include <vector> // the general-purpose vector container
  4. #include <iostream>
  5. #include <algorithm> // remove and remove_if
  6.  
  7. bool is_odd(int i)
  8. {
  9. return (i % 2) != 0;
  10. }
  11.  
  12. void print(const std::vector<int> &vec)
  13. {
  14. for (const auto& i: vec)
  15. std::cout << i << ' ';
  16. std::cout << std::endl;
  17. }
  18.  
  19. int main()
  20. {
  21. // initialises a vector that holds the numbers from 0-9.
  22. std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  23. print(v);
  24.  
  25. // removes all elements with the value 5
  26. v.erase( std::remove( std::begin(v), std::end(v), 5 ), std::end(v) );
  27. print(v);
  28.  
  29. // removes all odd numbers
  30. v.erase( std::remove_if(std::begin(v), std::end(v), is_odd), std::end(v) );
  31. print(v);
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 6 7 8 9 
0 2 4 6 8