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

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

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

3ds Max 2008
3ds Max 2008

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

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

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