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

struct Discounter {

  Inventory operator()(const Inventory& inv,

    float discount) {

    return Inventory(inv.getItem(),

      inv.getQuantity(),

      int(inv.getValue() * (1 - discount)));

  }

};

struct DiscGen {

  DiscGen() { srand(time(0)); }

  float operator()() {

    float r = float(rand() % 10);

    return r / 100.0;

  }

};

int main() {

  vector vi;

  generate_n(back_inserter(vi), 15, InvenGen());

  print(vi.begin(), vi.end(), "vi");

  vector disc;

  generate_n(back_inserter(disc), 15, DiscGen());

  print(disc.begin(), disc.end(), "Discounts:");

  vector discounted;

  transform(vi.begin(),vi.end(), disc.begin(),

    back_inserter(discounted), Discounter());

  print(discounted.begin(), discounted.end(),

        "discounted");

} ///:~

Given an Inventory object and a discount percentage, the Discounter function object produces a new Inventory with the discounted price. The DiscGen function object just generates random discount values between 1% and 10% to use for testing. In main( ), two vectors are created, one for Inventory and one for discounts. These are passed to transform( ) along with a Discounter object, and transform( ) fills a new vector called discounted.

<p>Numeric algorithms</p>

These algorithms are all tucked into the header , since they are primarily useful for performing numeric calculations.

T accumulate(InputIterator first, InputIterator last, T result); T accumulate(InputIterator first, InputIterator last, T result, BinaryFunction f);

The first form is a generalized summation; for each element pointed to by an iterator i in [first, last), it performs the operation result = result + *i, in which result is of type T. However, the second form is more general; it applies the function f(result, *i) on each element *i in the range from beginning to end.

Note the similarity between the second form of transform( ) and the second form of accumulate( ).

T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init); T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryFunction1 op1, BinaryFunction2 op2);

Calculates a generalized inner product of the two ranges [first1, last1) and [first2, first2 + (last1 - first1)). The return value is produced by multiplying the element from the first sequence by the "parallel" element in the second sequence and then adding it to the sum. Thus, if you have two sequences {1, 1, 2, 2} and {1, 2, 3, 4}, the inner product becomes.

(1*1) + (1*2) + (2*3) + (2*4)

which is 17. The init argument is the initial value for the inner product; this is probably zero but may be anything and is especially important for an empty first sequence, because then it becomes the default return value. The second sequence must have at least as many elements as the first.

The second form simply applies a pair of functions to its sequence. The op1 function is used in place of addition, and op2 is used instead of multiplication. Thus, if you applied the second version of inner_product( ) to the sequence, the result would be the following operations:

init = op1(init, op2(1,1));

init = op1(init, op2(1,2));

init = op1(init, op2(2,3));

init = op1(init, op2(2,4));

Thus, it’s similar to transform( ), but two operations are performed instead of one.

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

Calculates a generalized partial sum. This means that a new sequence is created, beginning at result; each element is the sum of all the elements up to the currently selected element in [first, last). For example, if the original sequence is {1, 1, 2, 2, 3}, the generated sequence is {1, 1 + 1, 1 + 1 + 2, 1 + 1 + 2 + 2, 1 + 1 + 2 + 2 + 3}, that is, {1, 2, 4, 6, 9}.

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

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

3ds Max 2008
3ds Max 2008

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

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

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