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

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

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

3ds Max 2008
3ds Max 2008

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

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

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