C++ STL algorithm, another replace() 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() 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)
{
// vector container
vector <int> vec1;
// vector iterator
vector <int>::iterator Iter1;
int i, j;
// push data in range
for(i = 0; i <= 9; i++)
vec1.push_back(i);
for(j = 0; j <= 2; j++)
vec1.push_back(5);
// randomly shuffle the data
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 with other values
replace (vec1.begin( ), vec1.end( ), 3, 23);
replace (vec1.begin( ), vec1.end( ), 7, 77);
replace (vec1.begin( ), vec1.end( ), 0, 21);
cout<<"\nThe vec1 vector data with replacement values of 0/21, 3/23, 7/77 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: 5 1 9 2 0 5 7 3 4 6 8 5 5
The vec1 vector data with replacement values of 0/21, 3/23, 7/77 is: 5 1 9 2 21 5 77 23 4 6 8 5 5
Press any key to continue . . .