株式会社エス・スリー・フォー

STL Samples : <map>

重複を許さない辞書

classmap

重複を許す辞書

classmultimap

source

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

using namespace std;

template<class Pair>
void print_pair(const Pair& x) {
  cout << '(' << x.first << ':' << x.second << ") ";
}

void std_map() {
  cout << "map" << endl;
  const char* number[] = { "zero", "one", "two", "three" };
  map<int,string> m;
  int i;
  for ( i = 0; i < 4; ++i )
    m[i] = number[i];

  map<int,string>::iterator it;
  for ( it = m.begin(); it != m.end(); ++it)
    print_pair(*it);
  cout << endl;

  for ( i = 2; i < 6; ++i ) {
    it = m.find(i);
    if ( it != m.end() )
      cout << "key:" << it->first << " --> value:" << it->second << endl;
    else
      cout << i << " not found." << endl;  
  }
}

void std_multimap() {
  cout << "multimap" << endl;
  const char* jp[] = { "いち", "に", "さん", "よん" };
  const char* uk[] = { "one ", "two", "three" };
  const char* gr[] = { "eins", "zwei" };

  multimap<int,string> m;
  int i;
  for ( i = 0; i < 4; ++i ) m.insert(make_pair(i+1,jp[i]));
  for ( i = 0; i < 3; ++i ) m.insert(make_pair(i+1,uk[i]));
  for ( i = 0; i < 2; ++i ) m.insert(make_pair(i+1,gr[i]));

  typedef multimap<int,string>::iterator iter;
  iter it;
  for ( it = m.begin(); it != m.end(); ++it)
    print_pair(*it);
  cout << endl;

  pair<iter,iter> range;
  for ( i = 0; i < 6; ++i ) {
    range = m.equal_range(i);
    if ( range.first != range.second ) {
      cout << "key:" << i << " --> value:";
      while ( range.first != range.second ) {
        cout << range.first->second << ' ';
        ++range.first;
      }
      cout << endl;
    } else {
      cout << i << " not found." << endl;  
    }
  }  
}