Dictionaries with std::map

Is There a Dictionary in C++?

C++ has no class named Dictionary, but std::map and std::unordered_map store key-value pairs. Here is how they compare, with a short example.

On this page
  1. What the standard library offers
  2. A short example
  3. Which one should you use?
  4. Plain C

Is there a dictionary in C++? Not with that name. C++ has no class called Dictionary, but its standard library has two containers that do the same job: std::map and std::unordered_map. Both store key-value pairs, so you can use a key, such as a country name, to find its value. This page compares the two and shows a short example. For a complete walkthrough of the basic operations on a std::map, see the guide to using a dictionary in C++ with std::map.

What the standard library offers

  • std::map, from <map>, keeps its entries sorted by key. Lookups, inserts and erases take time that grows with the logarithm of the number of entries. It is the usual choice when you want sorted output.
  • std::unordered_map, from <unordered_map>, has been available since C++11. It uses hashing, so lookups, inserts and erases take average constant time, and it does not keep its entries in any defined order.

A short example

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

int main() {
    std::map<std::string, std::string> capitals;
    capitals["France"] = "Paris";
    capitals["Japan"] = "Tokyo";

    std::cout << capitals["France"] << '\n';
}

This prints Paris. To use a hash table instead, change the declaration to std::unordered_map<std::string, std::string> capitals; and include <unordered_map>. The rest of the code stays the same.

Which one should you use?

Start with std::map if you are unsure, since its entries stay in key order. Consider std::unordered_map when you mostly look up single keys and do not need ordered output. If speed matters for your data, measure both with a realistic number of entries.

Plain C

The C standard library has no dictionary, map or hash table type. C programmers usually write their own hash table or use a third-party library. If you are working in C++, the standard containers above are the simpler choice.

The complete guide to dictionaries with std::map

How to Use a Dictionary in C++ With std::map
Read the guide

Keep exploring

Guides from other topics

All topics →

The final Keyword in C++

Learn how the final keyword in C++ stops a class from being inherited or a virtual function from being overridden, with short, working code examples.

final 4 min read

C++ String Methods

A guide to C++ string methods: std::string member functions like size, substr, find and replace, plus the C-style functions in <cstring>, with examples.

String Methods 5 min read