Use the generic remove algorithm : remove « STL Algorithms Modifying sequence operations « C++ Tutorial






#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
  const int  N = 11;
  int array1[N] = {1, 2, 0, 3, 4, 0, 5, 6, 7, 0, 8};
  vector<int> vector1;

  for (int i = 0; i < N; ++i)
    vector1.push_back(array1[i]);

  // Remove the zeros from vector1:
  vector<int>::iterator new_end;
  new_end = remove(vector1.begin(), vector1.end(), 0);

  for (int i = 0; i < (int)vector1.size(); ++i)
    cout << vector1[i];
  cout << "\n\n\n\n\n";
  // The size of vector1 remains the same:
  assert (vector1.size() == N);
  cout << vector1.size();

  cout << "\n\n\n\n\n";

  // The nonzero elements are left in [vector1.begin(), new_end).  Erase the rest:
  vector1.erase(new_end, vector1.end());

  // Show that 3 elements were removed and the nonzero elements remain, in their original order:
  assert (vector1.size() == N - 3);
  cout << vector1.size();
  cout << "\n\n\n\n\n";

  for (int i = 0; i < (int)vector1.size(); ++i)
    cout << vector1[i];

  return 0;
}
12345678708




11




8




12345678








24.8.remove
24.8.1.Use the generic remove algorithm
24.8.2.Use std::remove to delete all element in a vector by value
24.8.3.Remove an element and then erase that element
24.8.4.Combine remove and erase together
24.8.5.Use remove() to delete elements from a vector
24.8.6.std::remove does not change the size of the container,it moves elements forward to fill gaps created and returns the new 'end' position.
24.8.7.Remove value from a vector with remove()