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

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

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

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

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

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

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

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

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

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