// Demonstrating use of functors or function objects 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 Function Objects 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: " ; for_each(list2.begin(), list2.end(), show_int); cout << endl; list::iterator ip; ip = find_if(list2.begin(), list2.end(), greater_than_x(90)); if (ip !=list2.end()) cout << "The first number greater than 90 is: " << *ip << endl; else cout << "No number greater than 90 in list2" << endl; ip = find_if(list2.begin(), list2.end(), greater_than_x(100)); if (ip !=list2.end()) cout << "The first number greater than 100 is: " << *ip << endl; else cout << "No number greater than 100 in list2" << endl; cout << "Count of numbers > 40: " << count_if(list2.begin(), list2.end(), greater_than_x(40)) << endl; cout << "Count of numbers > 80: " << count_if(list2.begin(), list2.end(), greater_than_x(80)) << endl; }