C++ STL list, remove_if() 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_if() to erase elements from the list for which a specified predicate is satisfied in C++ programming
To show: How to use the C++ list, remove_if() to erase elements from the list for which a specified predicate is satisfied in C++ programming
// C++ STL list, remove_if()
#include <list>
#include <iostream>
using namespace std;
template <class T> class is_odd : public unary_function<T, bool>
{
public:
bool operator() (T& val)
{
return (val % 2) == 1;
}
};
int main(void)
{
// list container
list <int> con1;
// list iterator
list <int>::iterator con1_Iter, c2_Iter;
// push/insert data into the list
con1.push_back(13);
con1.push_back(41);
con1.push_back(24);
con1.push_back(25);
con1.push_back(36);
con1.push_back(20);
con1.push_back(71);
con1.push_back(8);
// print the data
cout<<"The initial list is con1: ";
for (con1_Iter = con1.begin(); con1_Iter != con1.end(); con1_Iter++)
cout<<" "<<*con1_Iter;
cout<<endl;
list <int> c2 = con1;
c2.remove_if(is_odd<int>());
cout<<"After removing the odd elements, the list becomes c2: ";
for (c2_Iter = c2.begin(); c2_Iter != c2.end(); c2_Iter++)
cout<<" "<<*c2_Iter;
cout<<endl;
return 0;
}
Output examples:
The initial list is con1: 13 41 24 25 36 20 71 8
After removing the odd elements, the list becomes c2: 24 36 20 8
Press any key to continue . . .