Читаем Thinking In C++. Volume 2: Practical Programming полностью

As another example, let’s count the number of elements in the sequence not equal to 20. This time we’ll use the algorithm count_if( ), introduced earlier. There is a standard binary function object, equal_to, and also a function object adapter, not1( ), that take a unary function object as a parameter and invert its truth value. The following program will do the job.

//: C06:CountNotEqual.cpp

// Count elements not equal to 20

#include

#include

#include

#include

using namespace std;

int main() {

  int a[] = {10, 20, 30};

  const size_t SIZE = sizeof a / sizeof a[0];

  cout << count_if(a, a + SIZE,

    not1(bind1st(equal_to(), 20)));// 2

} ///:~.

As remove_copy_if( ) did in the previous example, count_if( ) calls the predicate in its third argument (let’s call it n) for each element of its sequence and increments its internal counter each time true is returned. If, as before, we call the current element of the sequence by the name e, the statement.

if (n(e))

in the implementation of count_if is interpreted as

if (!bind1st(equal_to, 20)(e))

which of course ends up as

if (!equal_to(20, e))

because not1( ) returns the logical negation of the result of calling its unary function argument. The first argument to equal_to is 20 in this case because we used bind1st( ) instead of bind2nd( ). Since testing for equality is symmetric in its arguments, we could have used either bind1st( ) or bind2nd( ) in this example.

The following table shows the templates that generate the standard function objects, along with the kinds of expressions to which they apply.

NameTypeResult produced
plusBinaryFunctionarg1 + arg2
minusBinaryFunctionarg1 - arg2
multipliesBinaryFunctionarg1 * arg2
dividesBinaryFunctionarg1 / arg2
modulusBinaryFunctionarg1 % arg2
negateUnaryFunction- arg1
equal_toBinaryPredicatearg1 == arg2
not_equal_toBinaryPredicatearg1 != arg2
greaterBinaryPredicatearg1 > arg2
lessBinaryPredicatearg1 < arg2
greater_equalBinaryPredicatearg1 >= arg2
less_equalBinaryPredicatearg1 <= arg2
logical_andBinaryPredicatearg1 && arg2
logical_orBinaryPredicatearg1 || arg2
logical_notUnaryPredicate!arg1
unary_negateUnary Logical!(UnaryPredicate(arg1))
binary_negateBinary Logical!(BinaryPredicate(arg1, arg2))
<p>Adaptable function objects</p>

Standard function adapters such as bind1st( ) and bind2nd( ) make some assumptions about the function objects they process. To illustrate, consider the following expression from the last line of the earlier CountNotEqual.cpp program:.

not1(bind1st(equal_to(), 20))

The bind1st( ) adapter creates a unary function object of type binder1st, which simply stores an instance of equal_to and the value 20. The binder1st::operator( ) function needs to know its argument type and its return type; otherwise, it will not have a valid declaration. The convention to solve this problem is to expect all function objects to provide nested type definitions for these types. For unary functions, the type names are argument_type and result_type; for binary function objects they are first_argument_type, second_argument_type, and result_type. Looking at the implementation of bind1st( ) and binder1st in the header reveals these expectations. First inspect bind1st( ), as it might appear in a typical library implementation:.

template

binder1st

bind1st(const Op& f, const T& val)

{

  typedef typename Op::first_argument_type Arg1_t;

  return binder1st(f, Arg1_t(val));

}

Note that the template parameter, Op, which represents the type of the binary function being adapted by bind1st( ), must have a nested type named first_argument_type. (Note also the use of typename to inform the compiler that it is a member type name, as explained in Chapter 5.) Now notice how binder1st uses the type names in Op in its declaration of its function call operator:.

// Inside the implementation for binder1st

typename Op::result_type

operator()(const typename Op::second_argument_type& x)

  const;

Function objects whose classes provide these type names are called adaptable function objects.

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных