C++ STL algorithm, replace_if() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ replace_if() to examine each element in a range and replaces it if it satisfies a specified predicate in C++ programming

To show: How to use the C++ algorithm, replace_if() to examine each element in a range and replaces it if it satisfies a specified predicate in C++ programming

// C++ STL algorithm, replace_if()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

bool greaterthan(int value)

{return value > 4;}

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter1;

int i, j;

// push data in range

for (i = 1; i <= 10; i++)

vec1.push_back(i);

for (j = 0; j <= 2; j++)

vec1.push_back(8);

// shuffle the data randomly

random_shuffle(vec1.begin(), vec1.end());

cout<<"The original vec1 vector data randomly shuffled is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// replace elements satisfying the predicate greaterthan() with a value of 21

replace_if(vec1.begin(), vec1.end(), greaterthan, 21);

cout<<"\nThe vec1 vector with a value 21 replacing those\n "

<<"elements satisfying the greater than 4 predicate is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

The original vec1 vector data randomly shuffled is: 8 2 10 3 1 8 8 4 5 7 9 6 8

The vec1 vector with a value 21 replacing those

elements satisfying the greater than 4 predicate is: 21 2 21 3 1 21 21 4 21 21 21 21 21

Press any key to continue . . .