Читаем 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.

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

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

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

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