Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page