C++ STL algorithm, remove() 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() to eliminate a specified value 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: Using the C++ algorithm, remove() to eliminate a specified value 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()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// container

vector <int> vec1;

// iterator

vector <int>::iterator Iter1, new_end;

int i, j;

 

// push data in range

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

vec1.push_back(i);

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

vec1.push_back(8);

 

// print the data

cout<<"vec1 vector original 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<<"vec1 vector data randomly shuffled is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

// remove elements with a value of 8

new_end = remove(vec1.begin(), vec1.end(), 8);

cout<<"After remove() operation, vec1 vector data with 8 value 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<<"After erase() operation, vec1 vector resized data with 8 value removed is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

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

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

After remove() operation, vec1 vector data with 8 value removed is: 2 10 3 1 4 5 7 9 6 7 9 6 8

After erase() operation, vec1 vector resized data with 8 value removed is: 2 10 3 1 4 5 7 9 6

Press any key to continue . . .

 

 

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