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






Use the generic remove algorithm

  
 
#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
 */
        
    
  








Related examples in the same category

1.Use std::remove to delete all element in a vector by value
2.Remove an element and then erase that element
3.Combine remove and erase together
4.Remove all instances of '0'
5.Remove copy Elements if They Meet a Criterion
6.remove empty string