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

    if(count >= maxSize()) count = 0;

    result.first = letters[count++];

    int entries = (rand() % 5) + 2;

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

      int choice = rand() % maxSize();

      char cbuf[2] = { 0 };

      cbuf[0] = letters[choice];

      result.second.push_back(cbuf);

    }

    return result;

  }

};

int ThesaurusGen::count = 0;

const string ThesaurusGen::letters("ABCDEFGHIJKL"

  "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");

// Ask for a "word" to look up:

string menu(Thesaurus& thesaurus) {

  while(true) {

    cout << "Select a \"word\", 0 to quit: ";

    for(TIter it = thesaurus.begin();

      it != thesaurus.end(); it++)

      cout << (*it).first << ' ';

    cout << endl;

    string reply;

    cin >> reply;

    if(reply.at(0) == '0') exit(0); // Quit

    if(thesaurus.find(reply) == thesaurus.end())

      continue; // Not in list, try again

    return reply;

  }

}

int main() {

  Thesaurus thesaurus;

  // Fill with 10 entries:

  generate_n(

    inserter(thesaurus, thesaurus.begin()),

    10, ThesaurusGen());

  // Print everything:

  copy(thesaurus.begin(), thesaurus.end(),

    ostream_iterator(cout, "\n"));

  // Create a list of the keys:

  string keys[10];

  int i = 0;

  for(TIter it = thesaurus.begin();

    it != thesaurus.end(); it++)

    keys[i++] = (*it).first;

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

    // Enter from the console:

    // string reply = menu(thesaurus);

    // Generate randomly

    string reply = keys[rand() % 10];

    vector& v = thesaurus[reply];

    copy(v.begin(), v.end(),

      ostream_iterator(cout, " "));

    cout << endl;

  }

} ///:~

A Thesaurus maps a string (the word) to a vector (the synonyms). A TEntry is a single entry in a Thesaurus. By creating an ostream operator<< for a TEntry, a single entry from the Thesaurus can easily be printed (and the whole Thesaurus can easily be printed with copy( )). The ThesaurusGen creates "words" (which are just single letters) and "synonyms" for those words (which are just other randomly chosen single letters) to be used as thesaurus entries. It randomly chooses the number of synonym entries to make, but there must be at least two. All the letters are chosen by indexing into a static string that is part of ThesaurusGen.

In main( ), a Thesaurus is created, filled with 10 entries and printed using the copy( ) algorithm. The menu( ) function asks the user to choose a "word" to look up by typing the letter of that word. The find( ) member function discovers whether the entry exists in the map. (Remember, you don’t want to use operator[ ], which will automatically make a new entry if it doesn’t find a match!) If so, operator[ ] fetches out the vector that is displayed.

In the previous code, the selection of the reply string is generated randomly, to allow automated testing.

Because templates make the expression of powerful concepts easy, you can take this concept much further, creating a map of vectors containing maps, and so on. For that matter, you can combine any of the STL containers this way.

<p>Cleaning up containers of pointers</p>

In Stlshape.cpp, the pointers did not clean themselves up automatically. It would be convenient to be able to do this easily, rather than writing out the code each time. Here is a function template that will clean up the pointers in any sequence container; note that it is placed in the book’s root directory for easy access:

//: :purge.h

// Delete pointers in an STL sequence container

#ifndef PURGE_H

#define PURGE_H

#include

template void purge(Seq& c) {

  typename Seq::iterator i;

  for(i = c.begin(); i != c.end(); ++i) {

    delete *i;

    *i = 0;

  }

}

// Iterator version:

template

void purge(InpIt begin, InpIt end) {

  while(begin != end) {

    delete *begin;

    *begin = 0;

    begin++;

  }

}

#endif // PURGE_H ///:~

In the first version of purge( ), note that typename is absolutely necessary; indeed this is exactly the case that the keyword was added for: Seq is a template argument, and iterator is something that is nested within that template. So what does Seq::iterator refer to? The typename keyword specifies that it refers to a type, and not something else.

Although the container version of purge( ) must work with an STL-style container, the iterator version of purge( ) will work with any range, including an array.

Here is Stlshape.cpp, modified to use the purge( ) function:

//: C07:Stlshape2.cpp

// Stlshape.cpp with the purge() function

#include

#include

#include "../purge.h"

using namespace std;

class Shape {

public:

  virtual void draw() = 0;

  virtual ~Shape() {};

};

class Circle : public Shape {

public:

  void draw() { cout << "Circle::draw\n"; }

  ~Circle() { cout << "~Circle\n"; }

};

class Triangle : public Shape {

public:

  void draw() { cout << "Triangle::draw\n"; }

  ~Triangle() { cout << "~Triangle\n"; }

};

class Square : public Shape {

public:

  void draw() { cout << "Square::draw\n"; }

  ~Square() { cout << "~Square\n"; }

};

typedef std::vector Container;

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

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

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

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

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

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

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

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

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