// Demonstrating use of count_if and find_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 bool greater_than_50 (int x) { return x > 50 ? true : false; } bool even_p (int a) { return ! (a % 2); } 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: " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; // is there are a number in the list that satisfies a // particular predicate (or test) list::iterator ip; ip = find_if(list2.begin(), list2.end(), greater_than_50); if (ip !=list2.end()) cout << "The first number greater than 50 is: " << *ip << endl; else cout << "No number greater than 50 in list2" << endl; cout << "Number of items greater than 50 in list2: " << count_if(list2.begin(), list2.end(), greater_than_50) << endl; cout << "Number of even numbers in list2: " << count_if(list2.begin(), list2.end(), even_p) << endl; }