C++ STL algorithm, remove_copy_if() 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_if() to copy elements from a source range to a destination range, except that satisfying a predicate 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 C++ algorithm, remove_copy_if() to copy elements from a source range to a destination range, except that satisfying a predicate 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_if()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

bool greathan(int value)

{return value >7;}

 

int main(void)

{

// vector container

vector <int> vec1, vec2(14);

// 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<<"\nThe original vec1 vector data randomly shuffled: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// remove elements with a value greater than 7

new_end = remove_copy_if(vec1.begin(), vec1.end(), vec2.begin(), greathan);

cout<<"\nAfter the remove_copy_if() operation, the vec1 vector is left unchanged as: ";

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

cout<<*Iter1<<" ";

cout<<endl;

cout<<"\nvec2 vector is a copy of vec1 vector with values greater than 7 removed: ";

for(Iter2 = vec2.begin(); Iter2 != new_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: 5 1 9 2 0 5 7 3 4 6 8 5 10 5

After the remove_copy_if() operation, the vec1 vector is left unchanged as: 5 1 9 2 0 5 7 3 4 6 8 5 10 5

vec2 vector is a copy of vec1 vector with values greater than 7 removed: 5 1 2 0 5 7 3 4 6 5 5

Press any key to continue . . .

 

 

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