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

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

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

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

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

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

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

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

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

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