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

<p>Example</p>

This gives a basic demonstration of sequence manipulation:.

//: C06:Manipulations.cpp

// Shows basic manipulations

#include "PrintSequence.h"

#include "NString.h"

#include "Generators.h"

#include

#include

#include

using namespace std;

int main() {

  vector v1(10);

  // Simple counting:

  generate(v1.begin(), v1.end(), SkipGen());

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

  vector v2(v1.size());

  copy_backward(v1.begin(), v1.end(), v2.end());

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

  reverse_copy(v1.begin(), v1.end(), v2.begin());

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

  reverse(v1.begin(), v1.end());

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

  int half = v1.size() / 2;

  // Ranges must be exactly the same size:

  swap_ranges(v1.begin(), v1.begin() + half,

    v1.begin() + half);

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

  // Start with fresh sequence:

  generate(v1.begin(), v1.end(), SkipGen());

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

  int third = v1.size() / 3;

  for(int i = 0; i < 10; i++) {

    rotate(v1.begin(), v1.begin() + third,

      v1.end());

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

  }

  cout << "Second rotate example:" << endl;

  char c[] = "aabbccddeeffgghhiijj";

  const char csz = strlen(c);

  for(int i = 0; i < 10; i++) {

    rotate(c, c + 2, c + csz);

    print(c, c + csz, "", "");

  }

  cout << "All n! permutations of abcd:" << endl;

  int nf = 4 * 3 * 2 * 1;

  char p[] = "abcd";

  for(int i = 0; i < nf; i++) {

    next_permutation(p, p + 4);

    print(p, p + 4, "", "");

  }

  cout << "Using prev_permutation:" << endl;

  for(int i = 0; i < nf; i++) {

    prev_permutation(p, p + 4);

    print(p, p + 4, "", "");

  }

  cout << "random_shuffling a word:" << endl;

  string s("hello");

  cout << s << endl;

  for(int i = 0; i < 5; i++) {

    random_shuffle(s.begin(), s.end());

    cout << s << endl;

  }

  NString sa[] = { "a", "b", "c", "d", "a", "b",

    "c", "d", "a", "b", "c", "d", "a", "b", "c"};

  const int sasz = sizeof sa / sizeof *sa;

  vector ns(sa, sa + sasz);

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

  vector::iterator it =

    partition(ns.begin(), ns.end(),

      bind2nd(greater(), "b"));

  cout << "Partition point: " << *it << endl;

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

  // Reload vector:

  copy (sa, sa + sasz, ns.begin());

  it = stable_partition(ns.begin(), ns.end(),

    bind2nd(greater(), "b"));

  cout << "Stable partition" << endl;

  cout << "Partition point: " << *it << endl;

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

} ///:~

The best way to see the results of this program is to run it. (You’ll probably want to redirect the output to a file.)

The vector v1 is initially loaded with a simple ascending sequence and printed. You’ll see that the effect of copy_backward( ) (which copies into v2, which is the same size as v1) is the same as an ordinary copy. Again, copy_backward( ) does the same thing as copy( ); it just performs the operations in reverse order.

reverse_copy( ), however, actually does create a reversed copy, and reverse( ) performs the reversal in place. Next, swap_ranges( ) swaps the upper half of the reversed sequence with the lower half. Of course, the ranges could be smaller subsets of the entire vector, as long as they are of equivalent size.

After re-creating the ascending sequence, rotate( ) is demonstrated by rotating one third of v1 multiple times. A second rotate( ) example uses characters and just rotates two characters at a time. This also demonstrates the flexibility of both the STL algorithms and the print( ) template, since they can both be used with arrays of char as easily as with anything else.

To demonstrate next_permutation( ) and prev_permutation( ), a set of four characters "abcd" is permuted through all n! (n factorial) possible combinations. You’ll see from the output that the permutations move through a strictly defined order (that is, permuting is a deterministic process).

A quick-and-dirty demonstration of random_shuffle( ) is to apply it to a string and see what words result. Because a string object has begin( ) and end( ) member functions that return the appropriate iterators, it too can be easily used with many of the STL algorithms. Of course, an array of char could also have been used.

Finally, the partition( ) and stable_partition( ) are demonstrated, using an array of NString. You’ll note that the aggregate initialization expression uses char arrays, but NString has a char* constructor that is automatically used.

You’ll see from the output that with the unstable partition, the objects are correctly above and below the partition point, but in no particular order; whereas with the stable partition, their original order is maintained.

<p>Searching and replacing</p>

All these algorithms are used for searching for one or more objects within a range defined by the first two iterator arguments.

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

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

3ds Max 2008
3ds Max 2008

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

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

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