///////////////////////////////////////////////////////////////// // predicateFunction.cpp - demonstrates use of predicates // // with an STL algorithm // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2003 // ///////////////////////////////////////////////////////////////// #include #include #include using namespace std; //----< predicate function template ----------------------------- template bool isPositiveFunction(T& val) { return (val > 0); } template bool isPositiveFunction(int& val); // forces instantiation //----< predicate functor template ----------------------------- template class isPositiveFunctor : public unary_function { public: bool operator()(T val) const { return (val > 0); } }; //----< test >-------------------------------------------------- void main( ) { int array[7] = { 1,2,1,0,-1,-2,-3 }; list li(&array[0],&array[7]); // unary function pointer used in algorithm list::iterator iter = li.begin(); while(iter != li.end()) { iter = find_if(iter, li.end(), isPositiveFunction); if(iter != li.end()) cout << "\n positive element = " << *iter++; } cout << "\n\n"; // unary predicate functor used in algorithm iter = li.begin(); while(iter != li.end()) { iter = find_if(iter, li.end(), not1(isPositiveFunctor())); if(iter != li.end()) cout << "\n non-positive element = " << *iter++; } cout << "\n\n"; } positive element = 1 positive element = 2 positive element = 1 non-positive element = 0 non-positive element = -1 non-positive element = -2 non-positive element = -3