// Demonstrating use of replace and replace_if algorithms with list #include #include #include void show_int (int x) { cout << x << " "; } // sample PREDICATE functions -- take a parameter of same // type as the container, and pass back boolean if condition is true // Predicate works as a "filter" or "test" that can be applied on // STL containers with considerable convenience // 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 count_if and find_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(59); list2.push_back(89); list2.push_back(89); list2.push_back(49); cout << "LIST2 Elements (before replacements) : " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; replace(list2.begin(), list2.end(), 89, 400); cout << "LIST2 Elements (first replacement) : " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; replace_if(list2.begin(), list2.end(), greater_than_x(70), 200); cout << "LIST2 Elements (second replacement) : " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; }