Wednesday 25 July 2012

functional Library

<functional>


Functions in <functional> create function objects, which are objects that behave like functions by overloading operator(). These can be passed to algorithms that take function arguments, e.g.
vector<int> v(10);
sort(v.begin(), v.end(), greater<int>()); // Sort v in reverse order
int x=accumulate(v.begin(), v.end(), 1, multiplies<T>); // Product of elements
The following create function objects that take one or two parameters x and y of type T and return the indicated expression, i.e., equal_to<int>()(3,4) returns false. // Predicates (return bool)
equal_to<T>() // x==y
not_equal_to<T>() // x!=y
greater<T>() // x>y
less<T>() // x<y
greater_equal<T>() // x>=y
less_equal<T>() // x<=y
logical_and<bool>() // x&&y
logical_or<bool>() // x||y
logical_not<bool>() // !x (unary)

// Arithmetic operations (return T)
plus<T>() // x+y
minus<T>() // x-y
multiplies<T>() // x*y
divides<T>() // x/y
modulus<T>() // x%y
negate<T>() // -x (unary)
A binder converts a 2-argument function object into a 1-argument object by binding a fixed value c to the other argument, e.g. bind2nd(less<int>(), 10) returns a function object that takes one argument x and returns true if x<10. bind1st(f, c) // An object computing f(c,y)
bind2nd(f, c) // An object computing f(x,c)

i=find_if(v.begin(), v.end(), bind2nd(equal_to<int>(), 0)); // Find first 0
The following convert ordinary functions and member functions into function objects. All functions must be converted to be passed to bind1st and bind2nd. Member functions must also be converted to be passed to algorithms. ptr_fun(f) // Convert ordinary function f to object
mem_fun(&T::f) // Convert member function of class T
mem_fun_ref(T::f) // Same

i=find_if(v.begin(), v.end(), mem_fun(&string::empty)); // Find ""
transform(v.begin(), v.end(), v.begin(), bind2nd(ptr_fun(pow), 2.0)); // Square elements
not1() and not2() negate a unary or binary function object. not1(f) // Object computing !f(x)
not2(f) // Object computing !f(x,y)

i=find_if(v.begin(), v.end(), not1(bind2nd(equal_to<int>(), 0))); // Find nonzero

No comments:

Post a Comment