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

C++ examples for STL Algorithm:replace_copy

Description

Replacing values from a sequence using algorithms replace_copy

Demo Code

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

bool greater9(int); // predicate function prototype 

int main()/*from ww  w .  ja  v a2s . co  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 > v2(a, a + SIZE); // copy of a 
  vector< int > c1(a, a + SIZE); // copy of a 
  cout << "Vector v1 before replacing all 10s:\n             ";
  copy(v2.begin(), v2.end(), output);


  // copy from v2 to c1, replacing 10s with 100s 
  replace_copy(v2.begin(), v2.end(), c1.begin(), 10, 100);
  cout << "\nVector c1 after replacing all 10s in v2:\n              ";
  copy(c1.begin(), c1.end(), output);

}

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

Result


Related Tutorials