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

This same philosophy of packaging two items together is also used to insert elements into the map, but the pair is created as part of the instantiated map and is called value_type, containing the key and the value. So one option for inserting a new element is to create a value_type object, loading it with the appropriate objects and then calling the insert( ) member function for the map. Instead, the following example uses the aforementioned special feature of map: if you’re trying to find an object by passing in a key to operator[ ] and that object doesn’t exist, operator[ ] will automatically insert a new key-value pair for you, using the default constructor for the value object. With that in mind, consider an implementation of a word-counting program:

//: C07:WordCount.cpp

// Count occurrences of words using a map

#include "../require.h"

#include

#include

#include

#include

using namespace std;

typedef map WordMap;

typedef WordMap::iterator WMIter;

int main(int argc, char* argv[]) {

  char* fname = "WordCount.cpp";

  if(argc > 1) fname = argv[1];

  ifstream in(fname);

  assure(in, fname);

  WordMap wordmap;

  string word;

  while(in >> word)

    wordmap[word]++;

  for(WMIter w = wordmap.begin(); w != wordmap.end(); w++)

    cout << w->first << ": "

      << w->second << endl;

} ///:~

This example shows the power of zero-initialization. Consider this line of code from the program above:.

wordmap[word]++;

This increments the int associated with word. If there isn’t such a word yet in the map, a key-value pair for the word is automatically inserted, with the value initialized to zero by a call to the pseudo-constructor int( ), which returns a 0.

Printing the entire list requires traversing it with an iterator. (There’s no copy( ) shortcut for a map unless you want to write an operator<< for the pair in the map.) As previously mentioned, dereferencing this iterator produces a pair object, with the first member the key and the second member the value.

If you want to find the count for a particular word, you can use the array index operator, like this:

cout << "the: " << wordmap["the"] << endl;

You can see that one of the great advantages of the map is the clarity of the syntax; an associative array makes intuitive sense to the reader. (Note, however, that if "the" isn’t already in the wordmap, a new entry will be created!)

<p>Multimaps and duplicate keys</p>

A multimap is a map that can contain duplicate keys. At first this may seem like a strange idea, but it can occur surprisingly often. A phone book, for example, can have many entries with the same name.

Suppose you are monitoring wildlife, and you want to keep track of where and when each type of animal is spotted. Thus, you may see many animals of the same kind, all in different locations and at different times. So if the type of animal is the key, you’ll need a multimap. Here’s what it looks like:

//: C07:WildLifeMonitor.cpp

#include

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

class DataPoint {

  int x, y; // Location coordinates

  time_t time; // Time of Sighting

public:

  DataPoint() : x(0), y(0), time(0) {}

  DataPoint(int xx, int yy, time_t tm) :

    x(xx), y(yy), time(tm) {}

  // Synthesized operator=, copy-constructor OK

  int getX() const { return x; }

  int getY() const { return y; }

  const time_t* getTime() const { return &time }

};

string animal[] = {

  "chipmunk", "beaver", "marmot", "weasel",

  "squirrel", "ptarmigan", "bear", "eagle",

  "hawk", "vole", "deer", "otter", "hummingbird",

};

const int asz = sizeof animal/sizeof *animal;

vector animals(animal, animal + asz);

// All the information is contained in a

// "Sighting," which can be sent to an ostream:

typedef pair Sighting;

ostream&

operator<<(ostream& os, const Sighting& s) {

  return os << s.first << " sighted at x= " <<

    s.second.getX() << ", y= " << s.second.getY()

    << ", time = " << ctime(s.second.getTime());

}

// A generator for Sightings:

class SightingGen {

  vector& animals;

  enum { d = 100 };

public:

  SightingGen(vector& an) :

    animals(an) { srand(time(0)); }

  Sighting operator()() {

    Sighting result;

    int select = rand() % animals.size();

    result.first = animals[select];

    result.second = DataPoint(

      rand() % d, rand() % d, time(0));

    return result;

  }

};

// Display a menu of animals, allow the user to

// select one, return the index value:

int menu() {

  cout << "select an animal or 'q' to quit: ";

  for(int i = 0; i < animals.size(); i++)

    cout <<'['<< i <<']'<< animals[i] << ' ';

  cout << endl;

  string reply;

  cin >> reply;

  if(reply.at(0) == 'q') return 0;

  istringstream r(reply);

  int i;

  r >> i; // Converts to int

  i %= animals.size();

  return i;

}

typedef multimap DataMap;

typedef DataMap::iterator DMIter;

int main() {

  DataMap sightings;

  generate_n(

    inserter(sightings, sightings.begin()),

    50, SightingGen(animals));

  // Print everything:

  copy(sightings.begin(), sightings.end(),

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

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

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

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

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

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

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

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

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