Predicates:Unary Predicates and Binay Predicates
bool isPrime (int number);
list<int>::iterator pos;
pos = find_if (coll.begin(), coll.end(), //range
isPrime); //predicate //返回isPrime为True的第一个元素的位置。如果找不到符合条件的元素,则返回coll.end()的位置。
Binary predicates typically compare a specific property of two arguments.
class Person {
public:
string firstname() const;
string lastname() const;
...
};
bool personSortCriterion (const Person& p1, const Person& p2);
sort (coll. begin(), coll. end() , //range
personSortCriterion);//binary Predicate
Function Objects:
Functional arguments for algorithms don't have to be functions. They can be objects that behave
as functions
You could say that anything that behaves like a function is a function A functional behavior is something that you
can call by using parentheses and passing arguments.
All you have to do is define operator () with the appropriate parameter
types:
class X {
public:
//define "function call" operator
return-value operator() (arguments) const;
...
};
X fo;
...
fo(arg1, arg2); //call operator () for function object fo
Function objects are "smart functions."
Each function object has its own type
Function objects are usually faster than ordinary functions.
for_each函数类似的定义op对象必须有operator()定义。
namespace std {
template <class Iterator, class Operation>
Operation for_each (Iterator act, Iterator end, Operation op)
{
while (act != end) { //as long as not reached the end
op (*act); // - call op() for actual element
act++; // - move iterator to the next element
}
return op; }
}
}
Predefined Function Objects:
class less<>,greater<>,negate< >,multiplies<>