// Remove and remove_if algorithm (with erase) with STL #include #include #include void show_int (int x) { cout << x << " "; } // a function object is a class which overloads the // function call () operator // Like a function, you can "call" a function object // It can be used as a predicate, etc. in STL algorithm calls // A function object is MORE powerful than a function // because you can package additional data with an object class greater_than_x { public: greater_than_x(int v) { val=v; } bool operator() (int a) { return a > val ? true : false ; } private: int val; }; int main() { cout << "Demonstrating remove and remove_if with lists." << endl; list list2; list::iterator ip; // populating the list using "push_back" list2.push_back(89); list2.push_back(99); list2.push_back(89); list2.push_back(69); list2.push_back(64); list2.push_back(89); list2.push_back(89); list2.push_back(49); cout << "LIST2 Elements (before removals) : " ; for_each(list2.begin(), list2.end(), show_int); cout << endl; cout << "LIST2 size (before removals) : " << list2.size() << endl; // remove algorithm conveniently returns the iterator position // AFTER all retained positions. You should erase these to get // rid of traces of the elements that were removed ip = remove(list2.begin(), list2.end(), 99); list2.erase(ip, list2.end()); // needed to actually get rid of elements... cout << "LIST2 Elements after first removal : " ; for_each(list2.begin(), list2.end(), show_int); cout << endl; cout << "LIST2 size after first removal: " << list2.size() << endl; //ip = remove_if(list2.begin(), list2.end(), greater_than_x(60)); //list2.erase(ip, list2.end()); // needed to actually get rid of elements... list2.erase( remove_if(list2.begin(), list2.end(), greater_than_x(60)), list2.end() ); cout << "LIST2 Elements after second removal: " ; for_each(list2.begin(), list2.end(), show_int); cout << endl; cout << "LIST2 size after second removal: " << list2.size() << endl; }