A predicate is simply a function that returns either a boolean (true/false) value or an integer value. Following the normal C convention, an integer value is assumed to be true if non-zero, and false otherwise. An example function might be the following, which takes as argument an integer and returns true if the number represents a leap year, and false otherwise:
bool isLeapYear (unsigned int year) // return true if year is leap year { // millennia are leap years if (0 == year % 1000) return true; // every fourth century is if (0 == year % 400) return true; // every fourth year is if (0 == year % 4) return true; // otherwise not return false; }
A predicate is used as an argument, for example, in the generic algorithm named find_if(). This algorithm returns the first value that satisfies the predicate, returning the end-of-range value if no such element is found. Using this algorithm, the following locates the first leap year in a list of years:
list<int>::iterator firstLeap = find_if(aList.begin(), aList.end(), isLeapYear);