C++ STL algorithm, replace_copy() of the random shuffled vector into a list program example

 

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

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

 

// C++ STL algorithm, replace_copy()

#include <vector>

#include <list>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// containers

vector <int> v1;

list <int> L1 (15);

// iterator for containers

vector <int>::iterator Iter1;

list <int>::iterator L_Iter1;

int i, j, k;

 

// pushing data in ranges

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

v1.push_back(i);

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

v1.push_back(7);

 

// randomly shuffle the vector data

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

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

v1.push_back(1);

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

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

cout<<*Iter1<<" ";

cout<<endl;

// replace elements in one part of the vector, a value of 7 with a value of 70 and copy into another part of the vector

replace_copy(v1.begin(), v1.begin() + 14, v1.end()-15, 7 , 70);

cout<<"\nThe v1 vector with a value 70 replacing that of 7 (a portion), copied to another part is:\n";

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(v1.begin(), v1.begin() + 14,L1.begin(), 7, 1);

cout<<"\nThe L1 list, a copy of v1 vector with the value of 0 replacing that of 7 is:\n";

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

cout<<*L_Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The original shuffled 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 1 1

The v1 vector with a value 70 replacing that of 7 (a portion), copied to another part is:

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

The L1 list, a copy of v1 vector with the value of 0 replacing that of 7 is:

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

Press any key to continue . . .

 

 

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