Replacing values from a sequence using algorithms replace_if - C++ STL Algorithm

C++ examples for STL Algorithm:replace_if

Description

Replacing values from a sequence using algorithms replace_if

Demo Code

#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <iterator> // ostream_iterator 
using namespace std;

bool greater9(int); // predicate function prototype 

int main()/*from  w w w .  ja  v a 2  s .  c  o  m*/
{
  const int SIZE = 10;
  int a[SIZE] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };
  ostream_iterator< int > output(cout, " ");

  vector< int > v1(a, a + SIZE); // copy of a 
  vector< int > v3(a, a + SIZE); // copy of a 
  cout << "Vector v1 before replacing all 10s:\n             ";
  copy(v1.begin(), v1.end(), output);

  // replace values greater than 9 in v3 with 100 
  replace_if(v3.begin(), v3.end(), greater9, 100);
  cout << "\nVector v3 after replacing all values greater"
    << "\nthan 9 with 100s:\n        ";
  copy(v3.begin(), v3.end(), output);

}

// determine whether argument is greater than 9 
bool greater9(int x)
{
  return x > 9;
} // end function greater9

Result


Related Tutorials