I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

remove

Removes elements with a given value

Definition

The remove() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator, class Type >
   ForwardIterator remove(
      ForwardIterator first, 
      ForwardIterator last, 
      const Type& val
   );

Parameters:
Parameter Description
first A forward iterator addressing the position of the first element in the range from which elements are being removed
last A forward iterator addressing the position one past the final element in the range from which elements are being removed
val The value that is to be removed from the range

Description

Remove algorithm removes all elements that are equal to val from the range [first, last). (Uses operator!= to compare elements.)

Remove is stable, meaning that the relative order of elements that are not equal to val is unchanged.

Return Value

Returns the last removed element, or fi rst if fi rst and last are equal.

Complexity

The complexity is linear; performs (last - first) comparisons for equality.
Example:

Example - remove algorithm
Problem
This program illustrates the functionality of remove() algorithm.
Workings
#include <vector>
#include <algorithm>
#include <iostream>
 
using namespace std;
 
int main()
{
  vector <int> vec1;
  vector <int>::iterator Iter1, new_end;
  int i,j;
  for (i = 1; i <= 10; i++)
  vec1.push_back(i);
  for (j = 0; j <= 2; j++)
    vec1.push_back(8);
  cout <<"Vector vec1 original data: is\n";
  for (Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
    cout <<*Iter1<<" ";
  cout <<endl;
  random_shuffle(vec1.begin(), vec1.end());
  cout <<"Vector vec1 random shuffle data is:\n";
  for (Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
    cout <<*Iter1<<" ";
  cout <<endl;
  // remove elements with a value of 8
  new_end = remove(vec1.begin(), vec1.end(), 8);
  cout <<"Vector vec1 data with value 8 removed is:\n";
  for (Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
    cout <<*Iter1<<" ";
  cout <<endl;
  // using erase, to change the sequence size
  vec1.erase(new_end, vec1.end());
  cout <<"Vector vec1 resized data with value 8 removed is:\n";
  for (Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)
    cout <<*Iter1<<" ";
  cout <<endl;
 
  return 0;
}
Solution
Output:

Vector vec1 original data:
1 2 3 4 5 6 7 8 9 10 8 8 8
Vector vec1 random shuffle data is:
8 2 10 3 1 8 8 4 5 7 9 6 8
Vector vec1 data with value 8 removed is:
2 10 3 1 4 5 7 9 6 7 9 6 8
Vector vec1 resized data with value 8 removed is:
2 10 3 1 4 5 7 9 6
References