O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.6. Mapping strings to Other Things

Problem

You have objects that you need to store in memory, and you want to store them by their string keys. You need to be able to add, delete, and retrieve items quickly (with, at most, logarithmic complexity).

Solution

Use the standard container map, declared in <map>, to map keys (strings) to values (any type that obeys value semantics). Example 6-6 shows how.

Example 6-6. Creating a string map

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

using namespace std;

int main() {

   map<string, string> strMap;

   strMap["Monday"]    = "Montag";
   strMap["Tuesday"]   = "Dienstag";
   strMap["Wednesday"] = "Mittwoch";
   strMap["Thursday"]  = "Donnerstag";
   strMap["Friday"]    = "Freitag";
   strMap["Saturday"]  = "Samstag";
   // strMap.insert(make_pair("Sunday", "Sonntag"));
   strMap.insert(pair<string, string>("Sunday", "Sonntag"));

   for (map<string, string>::iterator p = strMap.begin();
      p != strMap.end(); ++p ) {
         cout << "English: " << p->first
              << ", German: " << p->second << endl;
   }

   cout << endl;

   strMap.erase(strMap.find("Tuesday"));

   for (map<string, string>::iterator p = strMap.begin();
      p != strMap.end(); ++p ) {
         cout << "English: " << p->first
              << ", German: " << p->second << endl;
   }
}

Discussion

A map is an associative container that maps keys to values, provides logarithmic complexity for inserting and finding, and constant time for erasing single elements. It is common for developers to use a map to keep track of objects by using a string key. This is what Example 6-6 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required