C++ std::map with key-value entries and iterator traversal

Maps in C++: A Practical std::map and Iterator Guide

To work with maps in C++, use std::map, an ordered associative container that stores unique keys with associated values. Keys are sorted automatically, so iterating over a map visits entries in key order.

This guide uses one small std::map named stock to show how you can declare, insert, access, update, find, erase, and traverse key-value entries.

Declare and initialize maps in C++: headers, types, and ordered keys

Include <map> for the container and <string> for string keys. The optional <iostream> header lets you print results.

#include <iostream>

#include <map>

#include <string>

The declaration below creates a map with std::string keys and int values. Each key identifies one stock count, and duplicate keys cannot coexist.

std::map<std::string, int> stock{{“apples”, 3}, {“oranges”, 2}, {“pears”, 4}};

Place that statement inside main() in a complete program. String keys are ordered lexicographically by default, so the map stores them in alphabetical order: apples, oranges, then pears. The map does not preserve the order in which you inserted entries.

Insert, access, and update values in a C++ map

Use insert() when you want to add a key-value pair without replacing an existing value.

stock.insert({“bananas”, 5});

If the key already exists, insert() leaves its value unchanged. It returns a pair whose second member is true when insertion succeeds:

auto result = stock.insert({“oranges”, 9});

Here, result.second is false because oranges is already present and still has the value 2. You can also use emplace() to construct an entry directly:

stock.emplace(“grapes”, 6);

Use operator[] for convenient access or updates. It changes an existing value when the key is present:

stock[“apples”] = 4;

However, operator[] inserts a missing key with a value-initialized value. For example, stock[“kiwis”] adds kiwis with the value 0 before returning it. This behavior is useful when you intentionally want to create an entry, but it can silently change the map during a read.

For read-only access that must not insert a key, use at() or find(). The expression stock.at(“oranges”) returns the value, while stock.at(“kiwis”) throws std::out_of_range if the key is absent.

Find and erase keys without silently inserting them

find() checks for a key without changing the map. It returns an iterator to the matching entry or stock.end() when no match exists.

auto found = stock.find(“pears”);

if (found != stock.end()) { std::cout << found->first << “: ” << found->second; }

The iterator’s first member is the key, and its second member is the value. This makes find() the safer choice when you need to test whether a key exists without creating it.

Erase by key when you do not need the entry’s iterator:

stock.erase(“pears”);

To erase the result of a search, check it first and pass the valid iterator to erase():

auto removable = stock.find(“bananas”);

if (removable != stock.end()) { stock.erase(removable); }

Iterate through entries with a C++ map iterator

A C++ map iterator moves through entries in ascending key order. Use begin() for the first entry and end() as the position just after the final entry.

for (std::map<std::string, int>::const_iterator it = stock.cbegin(); it != stock.cend(); ++it) { std::cout << it->first << “: ” << it->second << ‘\n’; }

cbegin() and cend() produce constant iterators, so this loop can read entries but cannot modify them. The ++it expression advances the iterator, and it->first and it->second access the key and value.

If you need to update values while traversing, use a non-constant iterator:

for (auto it = stock.begin(); it != stock.end(); ++it) { it->second += 1; }

Use auto to avoid repeating the full iterator type, while retaining the same begin(), comparison, increment, and member-access syntax.