C++ STL algorithm, remove_if() code 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_if() to eliminate elements that satisfy a predicate from a given range without disturbing the order of the remaining elements and returning the end of a new range free of the specified value in C++ programming

To show: How to use the C++ algorithm, remove_if() to eliminate elements that satisfy a predicate from a given range without disturbing the order of the remaining elements and returning the end of a new range free of the specified value in C++ programming

 

// C++ STL algorithm, remove_if()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

bool greathan(int value)

{return value >5;}

 

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter1, new_end;

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(4);

cout<<"Original vec1 vector data is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

 

// randomly shuffle the data

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

cout<<"\nvec1 vector data randomly shuffled is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// Remove elements satisfying predicate greater than

new_end = remove_if(vec1.begin(), vec1.end(), greathan);

cout<<"\nvec1 vector with elements greater than 5 removed is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// using erase, to change the sequence size,

vec1.erase(new_end, vec1.end());

cout<<"\nvec1 vector with resized elements greater than 5 removed is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

Original vec1 vector data is: 0 1 2 3 4 5 6 7 8 9 4 4 4

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

vec1 vector with elements greater than 5 removed is: 4 1 2 0 4 3 4 5 4 6 8 5 4

vec1 vector with resized elements greater than 5 removed is: 4 1 2 0 4 3 4 5 4

Press any key to continue . . .

 

 

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