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

Binary Predicate: A Binary Function that returns a bool.

Strict Weak Ordering: A binary predicate that allows for a more general interpretation of "equality." Some of the standard containers consider two elements equivalent if neither is less than the other (using operator<( )). This is important when comparing floating-point values, and objects of other types where operator==( ) is unreliable or unavailable. This notion also applies if you want to sort a sequence of data records (structs) on a subset of the struct’s fields, that comparison scheme is considered a strict weak ordering because two records with equal keys are not really "equal" as total objects, but they are equal as far as the comparison you’re using is concerned. The importance of this concept will become clearer in the next chapter.

In addition, certain algorithms make assumptions about the operations available for the types of objects they process. We will use the following terms to indicate these assumptions:.

LessThanComparable: A class that has a less-than operator<.

Assignable: A class that has a copy-assignment operator= for its own type.

EqualityComparable: A class that has an equivalence operator== for its own type.

We will use these terms later in this chapter to describe the generic algorithms in the standard library.

<p>Automatic creation of function objects</p>

The header defines a number of useful generic function objects. They are admittedly simple, but you can use them to compose more complicated function objects. Consequently, in many instances, you can construct complicated predicates without writing a single function yourself! You do so by using function object adapters to take the simple function objects and adapt them for use with other function objects in a chain of operations.

To illustrate, let’s use only standard function objects to accomplish what gt15( ) did earlier. The standard function object, greater, is a binary function object that returns true if its first argument is greater than its second argument. We cannot apply this directly to a sequence of integers through an algorithm such as remove_copy_if( ), because remove_copy_if( ) expects a unary predicate. No problem. We can construct a unary predicate on the fly that uses greater to compare its first argument to a fixed value. We fix the value of the second parameter that greater will use to be 15 with the function object adapter bind2nd, like this:.

//: C06:CopyInts4.cpp

// Uses a standard function object and adapter

#include

#include

#include

#include

#include

using namespace std;

int main() {

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

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

  remove_copy_if(a, a + SIZE,

  ostream_iterator(cout, "\n"),

  bind2nd(greater(), 15));

} ///:~.

This program accomplishes the same thing as CopyInts3.cpp, but without our having to write our own predicate function gt15( ). The function object adapter bind2nd( ) is a template function that creates a function object of type binder2nd, which simply stores the two arguments passed to bind2nd( ), the first of which must be a binary function or function object (that is, anything that can be called with two arguments). The operator( ) function in binder2nd, which is itself a unary function, calls the binary function it stored, passing it its incoming parameter and the fixed value it stored.

To make the explanation concrete for this example, let’s call the instance of binder2nd created by bind2nd( ) by the name b. When b is created, it receives two parameters (greater( ) and 15) and stores them. Let’s call the instance of greater by the name g. For convenience, let’s also call the instance of the output stream iterator by the name o. Then the call to remove_copy_if( ) earlier becomes the following:.

remove_copy_if(a, a + SIZE, o, b(g, 15).operator());

As remove_copy_if( ) iterates through the sequence, it calls b on each element, to determine whether to ignore the element when copying to the destination. If we denote the current element by the name e, that call inside remove_copy_if( ) is equivalent to.

if (b(e))

but binder2nd’s function call operator just turns around and calls g(e,15), so the earlier call is the same as.

if (greater(e, 15))

which is the comparison we were seeking. There is also a bind1st( ) adapter that creates a binder1st object, which fixes the first argument of the associated input binary function.

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

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

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

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

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

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

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

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

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