Back to notes -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    Illustration of the map standard container.Lecture 5 - slide 26 : 39
Program 1
// Reproduced from The C++ Programming Language, 3ed, page 483.
// Read strings and counts from standard input, and keep track of the
// sum for a particular string in the map. Also calculate the final total.

#include <iostream>
#include <string>
#include <map>

using namespace std;

void readitems(map<string, int> &m){
 string word;
 int val;
 while (cin >> word >> val)
   m[word] += val;             // Relies on the default map value initialization.
}

int main(){
  map<string,int> str_count;   // All values in the map are initialized to 0.

  readitems(str_count);

  int total = 0;
  typedef map<string,int>::const_iterator CI;
  
  // Accumulating total - and printing:
  for(CI it = str_count.begin(); it != str_count.end(); ++it){
    total += it->second;
    cout << it->first << "\t\t" << it->second << endl;
  }

  cout << "-------------------------\ntotal\t\t" << total << endl;
}