C++ STL algorithm, remove_copy() 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++ remove_copy() to copy elements from a source range to a destination range, except that elements of a specified value are not copied, without disturbing the order of the remaining elements and returning the end of a new destination range in C++ programming

To show: How to use the algorithm, remove_copy() to copy elements from a source range to a destination range, except that elements of a specified value are not copied, without disturbing the order of the remaining elements and returning the end of a new destination range in C++ programming

 

// C++ STL algorithm, remove_copy()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1, vec2(10);

// vector iterator

vector <int>::iterator Iter1, Iter2, new_end;

int i, j;

 

// push data in range

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

vec1.push_back(i);

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

vec1.push_back(5);

 

// print the data

cout<<"The original vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// 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;

// remove elements with a value of 5

new_end = remove_copy(vec1.begin(), vec1.end(), vec2.begin(), 5);

cout<<"After removing element = 5, vec1 vector is left unchanged as: ";

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

cout<<*Iter1<<" ";

cout<<endl;

cout<<"After removing element = 5, vec2 vector is a copy of vec1 with the value 5 removed is: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

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

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

After removing element = 5, vec1 vector is left unchanged as: 5 1 9 2 0 5 7 3 4 6 8 5 10 5

After removing element = 5, vec2 vector is a copy of vec1 with the value 5 removed is: 1 9 2 0 7 3 4 6 8 10

Press any key to continue . . .

 

 

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