A predicate is simply a function object that returns a value convertible to a bool. Here is an example of a predicate, which takes an integer as argument and returns true if the number represents a leap year, and false otherwise:
// return true if year is leap year
struct isLeapYear {
bool operator(unsigned int year) const {
// Every fourth century is a leap year
if (0 == year % 400) return true;
// ...but other centuries aren't.
if (0 == year % 100) return false;
// Otherwise, every fourth year is
if (0 == year % 4) return true;
// ...but all other years are not.
return false;
}
};
A predicate is used as an argument, for example, in the generic algorithm named std::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:
std::list<int>::iterator firstLeap = std::find_if(aList.begin(), aList.end(), isLeapYear);