many different function object adaptors, including unary_negate (which returns the logical complement of the value returned by a particular AdaptablePredicate), and unary_compose and binary_compose, which perform composition of function object.

Finally, the STL includes many different predefined function objects, including arithmetic operations (plus, minus, multiplies, divides, modulus, and negate), comparisons (equal_to, not_equal_to, greater, less, greater_equal, and less_equal), and logical operations (logical_and, logical_or, and logical_not). It is possible to perform very sophisticated operations without actually writing a new function object, simply by combining predefined function objects and function object adaptors.

Examples

Fill a vector with random numbers. In this example, the function object is simply a function pointer.

vector<int> V(100);

generate(V.begin(), V.end(), rand);

Sort a vector of double by magnitude, i.e. ignoring the elements' signs. In this example, the function object is an object of a user-defined class.

struct less_mag : public binary_function<double, double, bool> {

 bool operator()(double x, double y) { return fabs(x) < fabs(y); }

};

vector<double> V;

sort(V.begin(), V.end(), less_mag());

Find the sum of elements in a vector. In this example, the function object is of a user-defined class that has local state.

struct adder : public unary_function<double, void> {

 adder() : sum(0) {}

 double sum;

 void operator()(double x) { sum += x; }

};

vector<double> V;

adder result = for_each(V.begin(), V.end(), adder()); [3]

cout << 'The sum is ' << result.sum << endl;

Remove all elements from a list that are greater than 100 and less than 1000.

list<int> L;

list<int>::iterator new_end = remove_if(L.begin(), L.end(), compose2 (logical_and<bool>(), bind2nd(greater<int>(), 100), bind2nd(less<int>(), 1000)));

L.erase(new_end, L.end());

Concepts

• Generator

• Unary Function

• Binary Function

• Predicate

• Binary Predicate

• Adaptable Generator

• Adaptable Unary Function

• Adaptable Binary Function

• Adaptable Predicate

• Adaptable Binary Predicate

Types

• plus

• minus

• multiplies (formerly called times )

• divides

• modulus

• negate

• equal_to

• not_equal_to

• greater

• less

• greater_equal

• less_equal

• logical_and

• logical_or

• logical_not

• subtractive_rng

• identity

• project1st

• project2nd

• select1st

• select2nd

• unary_function

• binary_function

• unary_compose

• binary_compose

• unary_negate

• binary_negate

• binder1st

• binder2nd

• pointer_to_unary_function

• pointer_to_binary_function

Functions

• compose1

• compose2

• not1

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату