C++ STL algorithm, replace() 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() to examine each element in a range and replaces it if it matches a specified value in C++ programming

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

 

// C++ STL algorithm, replace()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// container

vector <int> v1;

// iterator

vector <int>::iterator Iter1;

int i, j;

 

// push data in range

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

v1.push_back(i);

// another push data in range

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

v1.push_back(9);

 

// randomly shuffle the data

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

 

// display 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 9 with a value of 90

replace(v1.begin(), v1.end(), 9, 90);

cout<<"The v1 vector with a value 90 replacing that of 9 is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

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

The v1 vector with a value 90 replacing that of 9 is: 90 1 90 2 0 90 7 3 4 6 8 5 90 90 10

Press any key to continue . . .

 

 

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