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

generate( ) makes a call to gen( ) for each element in the range [first, last), presumably to produce a different value for each element. generate_n( ) calls gen( ) n times and assigns each result to n elements starting at first.

<p>Example</p>

The following example fills and generates into vectors. It also shows the use of print( ):

//: C06:FillGenerateTest.cpp

// Demonstrates "fill" and "generate"

#include "Generators.h"

#include "PrintSequence.h"

#include

#include

#include

using namespace std;

int main() {

  vector v1(5);

  fill(v1.begin(), v1.end(), "howdy");

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

  vector v2;

  fill_n(back_inserter(v2), 7, "bye");

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

  vector v3(10);

  generate(v3.begin(), v3.end(), SkipGen(4,5));

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

  vector v4;

  generate_n(back_inserter(v4),15, URandGen(30));

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

} ///:~

A vector is created with a predefined size. Since storage has already been created for all the string objects in the vector, fill( ) can use its assignment operator to assign a copy of "howdy" to each space in the vector. Also, the default newline separator is replaced with a space.

The second vector v2 is not given an initial size, so back_inserter must be used to force new elements in instead of trying to assign to existing locations. Just as an example, the other print( ) is used, which requires a range.

The generate( ) and generate_n( ) functions have the same form as the "fill" functions except that they use a generator instead of a constant value; here, both generators are demonstrated.

<p>Counting</p>

All containers have a member function size( ) that will tells you how many elements they hold. The return type of size( ) is the iterator’s difference_type[87] (usually ptrdiff_t), which we denote by IntegralValue in the following. The following two algorithms count objects that satisfy certain criteria.

IntegralValue count(InputIterator first, InputIterator last, const EqualityComparable& value);

Produces the number of elements in [first, last) that are equivalent to value (when tested using operator==).

IntegralValue count_if(InputIterator first, InputIterator last, Predicate pred);

Produces the number of elements in [first, last) that each cause pred to return true.

<p>Example</p>

Here, a vector v is filled with random characters (including some duplicates). A set is initialized from v, so it holds only one of each letter represented in v. This set counts all the instances of all the characters, which are then displayed:.

//: C06:Counting.cpp

// The counting algorithms

#include

#include

#include

#include

#include

#include "Generators.h"

#include "PrintSequence.h"

using namespace std;

int main() {

  vector v;

  generate_n(back_inserter(v), 50, CharGen());

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

  // Create a set of the characters in v:

  set cs(v.begin(), v.end());

  typedef set::iterator sci;

  for(sci it = cs.begin(); it != cs.end(); it++) {

    int n = count(v.begin(), v.end(), *it);

    cout << *it << ": " << n << ", ";

  }

  int lc = count_if(v.begin(), v.end(),

    bind2nd(greater(), 'a'));

  cout << "\nLowercase letters: " << lc << endl;

  sort(v.begin(), v.end());

  print(v.begin(), v.end(), "sorted", "");

} ///:~

The count_if( ) algorithm is demonstrated by counting all the lowercase letters; the predicate is created using the bind2nd( ) and greater function object templates.

<p>Manipulating sequences</p>

These algorithms let you move sequences around.

OutputIterator copy(InputIterator first, InputIterator last, OutputIterator destination);

Using assignment, copies from [first, last) to destination, incrementing destination after each assignment. This is essentially a "shuffle-left" operation, and so the source sequence must not contain the destination. Because assignment is used, you cannot directly insert elements into an empty container or at the end of a container, but instead you must wrap the destination iterator in an insert_iterator (typically by using back_inserter( ) or by using inserter( ) in the case of an associative container).

BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 destinationEnd);

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

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

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

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

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

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

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

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

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