std::map
Ordered key-value storage.
std::map is a free C++ Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is std::map?
std::map stores key-value pairs sorted by key. Each key is unique, and lookups, insertions, and deletions run in logarithmic time.
- Keys are kept in sorted order.
- Backed by a balanced binary search tree.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
std::cout << "Alice is " << ages["Alice"] << '\n';
return 0;
}Inserting Elements
You can insert with operator[], insert(), or emplace(). Using [] on a missing key creates it with a default value.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m;
m["one"] = 1;
m.insert({"two", 2});
m.emplace("three", 3);
std::cout << m.size() << " entries\n";
return 0;
}Sorted Iteration
Iterating a std::map visits keys in ascending order. Each element is a std::pair with .first (key) and .second (value).
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"banana", 3}, {"apple", 5}, {"cherry", 1}};
for (const auto& p : m) {
std::cout << p.first << " = " << p.second << '\n';
}
return 0;
}Finding Keys
Use find() to safely look up a key. It returns an iterator to the element, or end() if not found.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"x", 10}, {"y", 20}};
auto it = m.find("y");
if (it != m.end()) {
std::cout << "Found y = " << it->second << '\n';
} else {
std::cout << "Not found\n";
}
return 0;
}Checking Existence
To test if a key exists without creating it, use count() (returns 0 or 1) or contains() in C++20.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"a", 1}};
std::cout << m.count("a") << '\n';
std::cout << m.count("z") << '\n';
return 0;
}Updating Values
Re-assigning a key updates its value in place. The map keeps only one value per key.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> score;
score["player"] = 10;
score["player"] += 5;
std::cout << score["player"] << '\n';
return 0;
}Erasing Elements
erase() removes an element by key or by iterator. It returns the number of elements removed when given a key.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};
m.erase("b");
std::cout << m.size() << " left\n";
for (const auto& p : m) std::cout << p.first << ' ';
std::cout << '\n';
return 0;
}Using at()
at() returns a reference to the value for a key and throws std::out_of_range if the key is missing. Unlike [], it never inserts.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"k", 42}};
std::cout << m.at("k") << '\n';
std::cout << "size: " << m.size() << '\n';
return 0;
}Counting Word Frequency
A classic use of std::map is counting occurrences. The [] operator default-initializes new keys to 0, so ++ just works.
#include <iostream>
#include <map>
#include <string>
int main() {
std::string words[] = {"cat", "dog", "cat", "bird", "dog", "cat"};
std::map<std::string, int> freq;
for (const auto& w : words) freq[w]++;
for (const auto& p : freq) std::cout << p.first << ": " << p.second << '\n';
return 0;
}Structured Bindings
C++17 lets you unpack each pair with structured bindings, giving readable names to key and value.
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> m{{"red", 1}, {"green", 2}};
for (const auto& [name, value] : m) {
std::cout << name << " -> " << value << '\n';
}
return 0;
}Checking If Empty
empty() reports whether the map has no elements, and clear() removes everything at once.
#include <iostream>
#include <map>
int main() {
std::map<int, int> m{{1, 1}, {2, 4}};
std::cout << std::boolalpha << m.empty() << '\n';
m.clear();
std::cout << m.empty() << '\n';
return 0;
}Quick Check
Test your understanding of std::map ordering.
Recap
You learned that std::map:
- stores unique sorted keys mapped to values
- supports
insert,[],find,count,at, anderase - iterates in ascending key order with pairs you can unpack via structured bindings
Next, you'll see std::set for storing just sorted unique values.
Frequently asked questions
Is the “std::map” lesson free?
Yes — the full text of “std::map” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “std::map”?
Ordered key-value storage. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “std::map” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.