Back to slide -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'          containers/maps/map-2.cpp - Illustration of the map standard container.Lecture 6 - slide 12 : 40
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;
  using CI = map<string,int>::const_iterator;    // C++11
  
  // Accumulating total - and printing - via use of const interator:
  for(CI it = str_count.begin(); it != str_count.end(); ++it){
    pair<string,int> element = *it;              // Emphasizing that keys and values are grouped in a pair.
    total += element.second;
    cout << element.first << "\t\t" << element.second << endl;
  }

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