C++ std::map

Beginner
8 min read
Updated: Nov 2026
3 examples
std::map

Definition and Usage

In C++, std::map<Key, T> is a container that stores key and value pairs. You look up a value by its key, like looking up a word in a dictionary. The keys are unique and the map always keeps them in sorted order.

Inside, a map is a balanced tree, so finding, inserting, and erasing a key all take logarithmic time. Read a value with at() or find(), and add pairs with insert() or emplace(). Include <map> to use it.

This page teaches what a std::map is. The Map Functions index lists every function guide in this series.

Why choose a map?

Choose a map when you need to connect keys to values and want the keys in order, for example names to ages, words to counts, or grade limits to letters. If you do not care about the order and want the fastest lookup, a std::unordered_map is often a better fit. If you only need a list of values by position, use a std::vector.

C++ Syntax

Common ways to create and use a std::map:

C++
#include <iostream>
#include <map>
#include <string>

std::map<std::string, int> a;                         // empty map
std::map<std::string, int> b = {{"b", 2}, {"a", 1}};  // sorted: a, b
std::map<int, std::string, std::greater<int>> c;      // biggest key first

b["c"] = 3;                      // add or update with []
b.insert({"d", 4});              // add only if the key is new
b.emplace("e", 5);               // build the pair in place
int x = b.at("a");               // 1 (throws if missing)
auto it = b.find("c");           // iterator, or b.end()
b.erase("d");                    // remove by key
std::size_t n = b.size();        // number of pairs

std::map vs std::unordered_map vs std::vector

Here is a quick comparison of three containers that beginners often mix up:

Featurestd::mapstd::unordered_mapstd::vector
StoresKey and value pairsKey and value pairsValues only
Order of elementsSorted by keyNo orderThe order you added them
Find by keyLogarithmicUsually constantLinear (search by value)
Duplicate keysNot allowedNot allowedNot applicable
Ordered search (lower_bound())YesNoOnly if you sort it
Key type needsoperator< or a comparatorA hash and operator==Not applicable
Header<map><unordered_map><vector>

When to Use find(), at() or []

All three read a value by key, but they react differently when the key is missing. Pick the one that fits:

Way to readIf the key is missingUse it when you…
find()Returns end(). The map is not changed.Are not sure the key exists, and want to handle both cases
at()Throws std::out_of_rangeExpect the key to exist and want a loud error if it does not
m[key]Adds the key with a default value (0, empty string, ...)Want to create or update on purpose, such as ++count[word]. It cannot be used on a const map.
contains() / count()Returns false or 0Only need to know whether a key exists
lower_bound()Returns the next bigger key, or end()Want the first key at or after a value

C++ Examples

Three short programs that show how std::map works.

Example 1 — Add Pairs and Loop in Key Order

A first program that adds pairs three different ways and prints them. The output is sorted by key, not by the order you wrote them.

C++
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> age;

    age["Raj"] = 25;
    age.insert({"Mia", 21});
    age.emplace("Zoe", 30);

    for (const auto& kv : age) {
        std::cout << kv.first << ": " << kv.second << '\n';
    }
    std::cout << "size: " << age.size() << '\n';
    return 0;
}

How It Works

  1. std::map<std::string, int> starts empty. The key is a name and the value is an age.
  2. age["Raj"] = 25, insert({"Mia", 21}), and emplace("Zoe", 30) each add one pair. The map puts every pair in its sorted place as it is added.
  3. The loop prints Mia, Raj, Zoe, which is alphabetical order and not the order of writing. size() counts the three pairs.

Example 2 — Read a Missing Key with find(), at() and []

The three ways to read a map act differently when the key is missing. This is the most important thing to learn about std::map.

C++
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>

int main() {
    std::map<std::string, int> stock = {{"apple", 5}};

    auto it = stock.find("kiwi");
    std::cout << (it == stock.end() ? "find: not found" : "find: found") << '\n';

    try {
        stock.at("kiwi");
    } catch (const std::out_of_range&) {
        std::cout << "at: threw out_of_range\n";
    }

    std::cout << "size before []: " << stock.size() << '\n';
    int n = stock["kiwi"];
    std::cout << "[] gave " << n << ", size after: " << stock.size() << '\n';
    return 0;
}

How It Works

  1. find("kiwi") returns end() because there is no such key. It never throws and it never changes the map.
  2. at("kiwi") throws std::out_of_range, so the catch block runs. The map is still unchanged, with 1 pair.
  3. stock["kiwi"] does not fail. It adds the key with the default value 0 and returns it. Even a read made the map bigger, and the size is now 2.

Example 3 — Count Words, then Search in Order with lower_bound()

A map is great for counting. Because its keys are sorted, you can also ask for the first key at or after a value.

C++
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = {"pear", "apple", "fig", "pear", "kiwi", "apple", "pear"};
    std::map<std::string, int> freq;

    for (const std::string& w : words) {
        ++freq[w];
    }

    for (const auto& kv : freq) {
        std::cout << kv.first << ": " << kv.second << '\n';
    }

    auto it = freq.lower_bound("g");
    if (it != freq.end()) {
        std::cout << "first word from g: " << it->first << '\n';
    }
    return 0;
}

How It Works

  1. ++freq[w] adds a new word with 0 and then increases it. A repeated word only raises its count, so pear ends at 3.
  2. The map holds four different words and prints them in alphabetical order, each with its count.
  3. lower_bound("g") returns the first key that is not smaller than "g". fig is smaller, so it skips to kiwi. The check against end() keeps the read safe.

Next: C++ std::map Functions Index

After you know what a std::map is, open the function index for a full tutorial on each member function.

Start withWhy
insert()Add a new key and value pair
find()Search for a key without adding it
erase()Remove a pair by key or by iterator
insert_or_assign()Add a key or update its value (C++17)

Full list: C++ std::map Functions index (/cpp/map/function).

Frequently Asked Questions

std::map<Key, T> is a container from <map>. It stores key and value pairs, keeps the keys sorted, and allows each key only once. You use a key to find its value quickly.
A map keeps keys in sorted order and finds a key in logarithmic time. An unordered_map uses hashing, has no order, and is usually faster to find a key. Choose map when you need sorted output or range searches such as lower_bound().
find() returns an iterator and gives end() for a missing key. at() returns the value but throws std::out_of_range for a missing key. m[key] never fails, but it adds a missing key with a default value, which changes the map.
No. Each key appears once. insert() and emplace() skip an existing key, while m[key] = value and insert_or_assign() replace its value. If you need duplicates, use std::multimap.
Open the C++ std::map Functions index. It lists every member function, from insert() and find() to lower_bound() and extract(), each with its own tutorial.

Browse every map function

Open the functions index for categorized guides with examples and FAQs.

Map Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful