Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
1715
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 22

Note that the product() function is passed as a callback to accumulate() and that the initial value for the accumulation is 1 (the identity for multiplication) instead of 0. The next section shows you how to use accumulate() in the geometricMean() function without writing a function callback.

Function Objects

Now that you’ve seen a few STL algorithms, you are able to appreciate function objects. Recall from Chapter 16 that you can overload the function call operator in a class such that objects of the class can be used in place of function pointers. These objects are called function objects, or just functors.

Many of the STL algorithms, such as find_if() and the second form of accumulate(), require a function pointer as one of the parameters. When you use these functions, you can pass a functor instead of a function pointer. That fact, in and of itself, is not necessarily cause for jumping up and down with joy.

While you can certainly write your own functor classes, the real attraction is that C++ provides several predefined functor classes that perform the most commonly used callback operations. This section describes these predefined classes and shows you how to use them.

All the predefined function object classes are located in the <functional> header file.

Arithmetic Function Objects

C++ provides functor class templates for the five binary arithmetic operators: plus, minus, multiplies, divides, and modulus. Additionally, unary negate is supplied. These classes are templatized on the type of the operands and are wrappers for the actual operators. They take one or two parameters of the template type, perform the operation, and return the result. Here is an example using the plus class template:

#include <functional> #include <iostream> using namespace std;

int main(int argc, char** argv)

{

plus<int> myPlus;

int res = myPlus(4, 5); cout << res << endl;

return (0);

}

This example is silly, because there’s no reason to use the plus class template when you could just use operator+ directly. The benefit of the arithmetic function objects is that you can pass them as callbacks to algorithms, which you cannot do directly with the arithmetic operators.

For example, the implementation of the geometricMean() function earlier in this chapter used the accumulate() function with a function pointer callback to multiply two integers. You could rewrite it to use the multiplies function object:

624

Mastering STL Algorithms and Function Objects

#include <numeric> #include <vector> #include <cmath> #include <functional> using namespace std;

double geometricMean(const vector<int>& nums)

{

double mult = accumulate(nums.begin(), nums.end(), 1,

multiplies<int>());

return (pow(mult, 1.0 / nums.size()));

}

The expression multiplies<int>() creates a new object of the multiplies class, instantiating it with the int type.

The other arithmetic function objects behave similarly.

The arithmetic function objects are just wrappers around the arithmetic operators. If you use the function objects as callbacks in algorithms, make sure that the objects in your container implement the appropriate operation, such as operator* or operator+.

Comparison Function Objects

In addition to the arithmetic function object classes, the C++ language provides all the standard comparisons: equal_to, not_equal_to, less, greater, less_equal, and greater_equal. You’ve already seen less in Chapter 21 as the default comparison for elements in the priority_queue and the associative containers. Now you can learn how to change that criterion. Here’s an example of a priority_queue using the default comparison operator: less.

#include <queue> #include <iostream> using namespace std;

int main(int argc, char** argv)

{

priority_queue<int> myQueue;

myQueue.push(3);

myQueue.push(4);

myQueue.push(2);

myQueue.push(1);

while (!myQueue.empty()) {

cout << myQueue.top() << endl; myQueue.pop();

}

return (0);

}

625

Chapter 22

The output from the program looks like this:

4

3

2

1

As you can see, the elements of the queue are removed in descending order, according to the less comparison. You can change the comparison to greater by specifying it as the comparison template argument. Recall from chapter 21 that the priority_queue template definition looks like this:

template <typename T, typename Container = vector<T>, typename Compare = less<T> >;

Unfortunately, the Compare type parameter is last, which means that in order to specify the comparison you must also specify the container. Here is an example of the above program modified so that the priotity_queue sorts elements in ascending order using greater:

#include <queue> #include <functional> #include <iostream> using namespace std;

int main(int argc, char** argv)

{

priority_queue<int, vector<int>, greater<int> > myQueue;

myQueue.push(3);

myQueue.push(4);

myQueue.push(2);

myQueue.push(1);

while (!myQueue.empty()) {

cout << myQueue.top() << endl; myQueue.pop();

}

return (0);

}

The output now looks like this:

1

2

3

4

Several algorithms that you will learn about later in this chapter require comparison callbacks, for which the predefined comparators come in handy.

626

Mastering STL Algorithms and Function Objects

Logical Function Objects

C++ also provides function object classes for the three logical operations: logical_not, logical_and, and logical_or. However, they are not typically useful with the standard STL.

Function Object Adapters

When you try to use the basic function objects provided by the standard, it often feels as if you’re trying to put a square peg into a round hole. For example, you can’t use the basic comparison function objects with find_if() because find_if() passes only one argument to its callback each time instead of two. The function adapters attempt to rectify this problem and others. They provide a modicum of support for functional composition, or combining functions together to create the exact behavior you need.

Binders

Suppose that you want to use the find_if() algorithm to find the first element in a sequence that is greater than or equal to 100. To solve this problem earlier in the chapter, we wrote a function perfectScore() and passed a function pointer to it to find_if(). Now that you know about the comparison functors, it seems as if you should be able to implement a solution using the greater_equal class template.

The problem with greater_equal is that it takes two parameters, whereas find_if() passes only one parameter to its callback predicate each time. You need the ability to specify that find_if() should use greater_equal, but should pass 100 as the second argument each time. That way, each element of the sequence will be compared against 100. Luckily, C++ gives you a way to say exactly that:

#include <algorithm> #include <vector> #include <iostream> #include <functional> using namespace std;

int main(int argc, char** argv)

{

int num;

vector<int> myVector; while (true) {

cout << “Enter a test score to add (0 to stop): “; cin >> num;

if (num == 0) { break;

}

myVector.push_back(num);

}

vector<int>::iterator it = find_if(myVector.begin(), myVector.end(),

bind2nd(greater_equal<int>(), 100));

627

Chapter 22

if (it == myVector.end()) {

cout << “No perfect scores\n”; } else {

cout << “Found a \”perfect\” score of “ << *it << endl;

}

return (0);

}

The bind2nd() function is called a binder because it “binds” the value 100 as the second parameter to greater_equal. The result is that find_if() compares each element against 100 with greater_equal.

You can use bind2nd() with any binary function. There is also an equivalent bind1st() function that binds an argument to the first parameter of a binary function.

Negators

The negators are functions similar to the binders that simply negate the result of a predicate. For example, if you wanted to find the first element in a sequence of test scores less than 100, you could apply a negator adapter to the result of greater_equal like this:

int main(int argc, char** argv)

{

int num;

vector<int> myVector; while (true) {

cout << “Enter a test score to add (0 to stop): “; cin >> num;

if (num == 0) { break;

}

myVector.push_back(num);

}

vector<int>::iterator it = find_if(myVector.begin(), myVector.end(),

not1(bind2nd(greater_equal<int>(), 100))); if (it == myVector.end()) {

cout << “All perfect scores\n”; } else {

cout << “Found a \”less-than-perfect\” score of “ << *it << endl;

}

return (0);

}

The function not1() negates the result of every call to the predicate it takes as an argument. Of course, you could also just use less instead of greater_equal. There are cases, often when using nonstandard functors, that not1() comes in handy. The “1” in not1() refers to the fact that its operand must be a unary function (one that takes a single argument). If its operand is a binary function (takes two arguments), you must use not2() instead. Note that you use not1() in this case because, even though greater_equal is a binary function, bind2nd() has already converted it to a unary function, by binding the second argument always to 100.

628

Mastering STL Algorithms and Function Objects

As you can see, using functors and adapters can quickly become complicated. Our advice is to limit their use to simple cases where the intention is clearly understandable, and to write your own functors or employ explicit loops for more complicated situations.

Calling Member Functions

If you have a container of objects, you sometimes want to pass a pointer to a class method as the callback to an algorithm. For example, you might want to find the first empty string in a vector of strings by calling empty() on each string in the sequence. However, if you just pass a pointer to string::empty() to find_if(), the algorithm has no way to know that it received a pointer to a method instead of a normal function pointer or functor. As explained in Chapter 9, the code to call a method pointer is different from that to call a normal function pointer, because the former must be called in the context of an object. Thus, C++ provides a conversion function called mem_fun_ref() that you can call on a method pointer before passing it to an algorithm (the “fun” in mem_fun_ref() refers to “function” and in no way implies that using it is fun). You can use it like this:

#include <functional> #include <algorithm> #include <string> #include <vector> #include <iostream> using namespace std;

void findEmptyString(const vector<string>& strings)

{

vector<string>::const_iterator it = find_if(strings.begin(), strings.end(), mem_fun_ref(&string::empty));

if (it == strings.end()) {

cout << “No empty strings!\n”; } else {

cout << “Empty string at position: “ << it - strings.begin() << endl;

}

}

mem_fun_ref() generates a function object that serves as the callback for find_if(). Each time it is called back, it calls the empty() method on its argument.

mem_fun_ref() works for both 0-argument and unary methods. The result can be used as the callback where a unary or binary function is expected, respectively.

If you have a container of pointers to objects instead of objects themselves, you must use a different function adapter, mem_fun(), to call member functions. For example:

#include <functional> #include <algorithm> #include <string> #include <vector> #include <iostream> using namespace std;

629