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

C++ examples for STL Algorithm:replace_copy_if

Description

Replacing values from a sequence using algorithms replace_copy_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  ww w .  j  ava  2 s .com
{ 
    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 
   cout << "Vector v1 before replacing all 10s:\n             "; 
   copy( v1.begin(), v1.end(), output ); 


   vector< int > v4( a, a + SIZE ); // copy of a 
   vector< int > c2( SIZE ); // instantiate vector c2? 
   cout << "\n\nVector v4 before replacing all values greater " 
       << "than 9 and copying:\n        "; 
   copy( v4.begin(), v4.end(), output ); 

   // copy v4 to c2, replacing elements greater than 9 with 100 
    replace_copy_if( v4.begin(), v4.end(), c2.begin(), greater9, 100 ); 
   cout << "\nVector c2 after replacing all values greater " 
       << "than 9 in v4:\n       "; 
   copy( c2.begin(), c2.end(), output ); 
   cout << endl; 
}

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

Result


Related Tutorials