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

In the second version, the binary function op is used instead of the + operator to take all the "summation" up to that point and combine it with the new value. For example, if you use multiplies( ) as the object for the sequence, the output is {1, 1, 2, 4, 12}. Note that the first output value is always the same as the first input value.

The return value is the end of the output range [result, result + (last - first) ).

OutputIterator adjacent_difference(InputIterator first, InputIterator last, OutputIterator result); OutputIterator adjacent_difference(InputIterator first, InputIterator last, OutputIterator result, BinaryFunction op);

Calculates the differences of adjacent elements throughout the range [first, last). This means that in the new sequence, the value is the value of the difference of the current element and the previous element in the original sequence (the first value is unchanged). For example, if the original sequence is {1, 1, 2, 2, 3}, the resulting sequence is {1, 1 – 1, 2 – 1, 2 – 2, 3 – 2}, that is: {1, 0, 1, 0, 1}.

The second form uses the binary function op instead of the – operator to perform the "differencing." For example, if you use multiplies( ) as the function object for the sequence, the output is {1, 1, 2, 4, 6}.

The return value is the end of the output range [result, result + (last - first) ).

<p>Example</p>

This program tests all the algorithms in in both forms, on integer arrays. You’ll notice that in the test of the form where you supply the function or functions, the function objects used are the ones that produce the same result as form one, so the results will be exactly the same. This should also demonstrate a bit more clearly the operations that are going on and how to substitute your own operations.

//: C06:NumericTest.cpp

//{L} ../TestSuite/Test

#include "PrintSequence.h"

#include

#include

#include

#include

#include

using namespace std;

int main() {

  int a[] = { 1, 1, 2, 2, 3, 5, 7, 9, 11, 13 };

  const int asz = sizeof a / sizeof a[0];

  print(a, a + asz, "a", " ");

  int r = accumulate(a, a + asz, 0);

  cout << "accumulate 1: " << r << endl;

  // Should produce the same result:

  r = accumulate(a, a + asz, 0, plus());

  cout << "accumulate 2: " << r << endl;

  int b[] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2 };

  print(b, b + sizeof b / sizeof b[0], "b", " ");

  r = inner_product(a, a + asz, b, 0);

  cout << "inner_product 1: " << r << endl;

  // Should produce the same result:

  r = inner_product(a, a + asz, b, 0,

    plus(), multiplies());

  cout << "inner_product 2: " << r << endl;

  int* it = partial_sum(a, a + asz, b);

  print(b, it, "partial_sum 1", " ");

  // Should produce the same result:

  it = partial_sum(a, a + asz, b, plus());

  print(b, it, "partial_sum 2", " ");

  it = adjacent_difference(a, a + asz, b);

  print(b, it, "adjacent_difference 1"," ");

  // Should produce the same result:

  it = adjacent_difference(a, a + asz, b,

    minus());

  print(b, it, "adjacent_difference 2"," ");

} ///:~

Note that the return value of inner_product( ) and partial_sum( ) is the past-the-end iterator for the resulting sequence, so it is used as the second iterator in the print( ) function.

Since the second form of each function allows you to provide your own function object, only the first form of the functions is purely "numeric." You could conceivably do some things that are not intuitively numeric with something like inner_product( ).

<p>General utilities</p>

Finally, here are some basic tools that are used with the other algorithms; you may or may not use them directly yourself.

struct pair; make_pair( );

This was described and used earlier in this chapter. A pair is simply a way to package two objects (which may be of different types) together into a single object. This is typically used when you need to return more than one object from a function, but it can also be used to create a container that holds pair objects or to pass more than one object as a single argument. You access the elements by saying p.first and p.second, in which p is the pair object. The function equal_range( ), described in the last chapter and in this one, returns its result as a pair of iterators. You can insert( ) a pair directly into a map or multimap; a pair is the value_type for those containers.

If you want to create a pair "on the fly,", you typically use the template function make_pair( ) rather than explicitly constructing a pair object.

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

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

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

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

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

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

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

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

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