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

Chapter 22

void findEmptyString(const vector<string*>& strings)

{

vector<string*>::const_iterator it = find_if(strings.begin(), strings.end(),

mem_fun(&string::empty));

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

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

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

}

}

Adapting Real Functions

You can’t use normal function pointers directly with the function adapters bind1st(), bind2nd(), not1(), or not2(), because these adapters require specific typedefs in the function objects they adapt. Thus, one last function adapter provided by the C++ standard library, ptr_fun(), allows you to wrap regular function pointers in a way that they can be used with the adapters. It is useful primarily for using legacy C functions, such as those in the C Standard Library. If you write your own callbacks, we encourage you to write function object classes, as described in the next section.

For example, suppose that you want to write a function isNumber() that returns true if every character in a string is a digit. As explained in Chapter 21, the C++ string provides an iterator. Thus, you can use the find_if() algorithm to search for the first nondigit in the string. If you find one, the string is not a number. The <cctype> header file provides a legacy C function called isdigit(), which returns true if a character is a digit, false otherwise. The problem is that you want to find the first character that is not a digit, which requires the not1() adapter. However, because isdigit() is a C function, not a function object, you need to use the ptr_fun() adapter to generate a function object that can be used with not1(). The code looks like this:

#include <functional> #include <algorithm> #include <cctype> #include <string> using namespace std;

bool isNumber(const string& str)

{

string::const_iterator it = find_if(str.begin(), str.end(), not1(ptr_fun(::isdigit)));

return (it == str.end());

}

Note the use of the :: scope resolution operator to specify that isdigit() should be found in the global scope.

Writing Your Own Function Objects

You can, of course, write your own function objects to perform more specific tasks than those provided by the predefined functors. If you want to be able to use the function adapters with these functors, you must supply certain typedefs. The easiest way to do that is to subclass your function object classes from

630