C++ STL algorithm, replace_copy_if() greater than 6 code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

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_copy_if() greater than 6 to examine each element in a source range and replaces it if it satisfies a specified predicate while copying the result into a new destination range in C++ programming

To show: How to use the C++ algorithm, replace_copy_if() to examine each element in a source range and replaces it if it satisfies a specified predicate while copying the result into a new destination range in C++ programming

 

// C++ STL algorithm, replace_copy_if()

#include <vector>

#include <list>

#include <algorithm>

#include <iostream>

using namespace std;

 

bool greater6(int value)

{

return (value > 6);

}

 

int main(void)

{

// containers

vector <int> v1;

list <int> L1 (13);

 

// iterators for containers

vector <int>::iterator Iter1;

list <int>::iterator L_Iter1;

int i, j, k;

 

// pushing data into the containers

for (i = 0 ; i <= 9 ; i++)

v1.push_back(i);

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

v1.push_back(7);

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

for (k = 0; k <= 13; k++)

v1.push_back(1);

 

// printing the data

cout<<"The original v1 vector is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// replace elements with a value of 7 in the 1st half of a vector with a value of 70 and copy it into the 2nd half of the vector

replace_copy_if(v1.begin(), v1.begin() + 14,v1.end() -14, greater6, 70);

cout<<"\nThe v1 vector with values of 70 replacing those greater"

<<"\n than 6 in the 1st half & copied into the 2nd half is: "<<endl;

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

cout<<*Iter1<<" ";

cout<<endl;

// replace elements in a vector with a value of 70 with a value of -1 and copy into a list

replace_copy_if(v1.begin(), v1.begin() + 13,L1.begin(), greater6, -1);

cout<<"\nA list copy of v1 vector with the value -1\n replacing those greater than 6 is: ";

for (L_Iter1 = L1.begin(); L_Iter1 != L1.end(); L_Iter1++)

cout<<*L_Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The original v1 vector is: 7 1 9 2 0 7 7 3 4 6 8 5 7 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1

The v1 vector with values of 70 replacing those greater

than 6 in the 1st half & copied into the 2nd half is:

7 1 9 2 0 7 7 3 4 6 8 5 7 7 70 1 70 2 0 70 70 3 4 6 70 5 70 70

A list copy of v1 vector with the value -1

replacing those greater than 6 is: -1 1 -1 2 0 -1 -1 3 4 6 -1 5 -1

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index