// Demonstrating remove and remove_if algorithm 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; // 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; // NOTE THAT REMOVE DOES NOT REALLY CHANGE SIZE // It essentially removes all occurences of an element // but, it leaves undefined slots at the end!! // remove algorithm returns the iterator position // at the first element after the retained elements... remove(list2.begin(), list2.end(), 99); 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; remove_if(list2.begin(), list2.end(), greater_than_x(60)); 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; }