C++ STL list, remove() code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

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 erase elements in a list that match a specified value in C++ programming

To show: How to use the C++ list, remove() to erase elements in a list that match a specified value in C++ programming

 

// C++ STL list, remove()

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

// list container

list <int> lis1;

// list iterators

list <int>::iterator lis1Iter, lis2Iter;

 

// insert/push data into the list

lis1.push_back(7);

lis1.push_back(12);

lis1.push_back(25);

lis1.push_back(7);

lis1.push_back(9);

lis1.push_back(7);

lis1.push_back(21);

 

// print the data and do some operations

cout<<"The initial lis1 list data is: ";

for(lis1Iter = lis1.begin(); lis1Iter != lis1.end(); lis1Iter++)

cout<<" "<<*lis1Iter;

cout<<endl;

cout<<"\nOperation1: list <int> lis2 = lis1;"<<endl;

cout<<"Operation2: lis2.remove(7);"<<endl;

list <int> lis2 = lis1;

lis2.remove(7);

cout<<"Removing elements of value 7, the list data, lis2 list is: ";

for(lis2Iter = lis2.begin(); lis2Iter != lis2.end(); lis2Iter++)

cout<<" "<<*lis2Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

The initial lis1 list data is: 7 12 25 7 9 7 21

Operation1: list <int> lis2 = lis1;

Operation2: lis2.remove(7);

Removing elements of value 7, the list data, lis2 list is: 12 25 9 21

Press any key to continue . . .

 

 

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