C++ Tutorial

C++ Map

map stores key-value pairs in order. Lookup by key instead of scanning a list.

Lookup by key

A vector answers “what is at index 2?” A map answers “what value sits under this key?” The key might be a part name, a user id, or a word. You do not walk the whole list to find it.

Include <map>. The type is map<Key, Value>. This chapter usesmap<string, int>: a string key and an integer value. StudyGrid compiles these programs as C++17.

Insert with []

stock["nails"] = 40; creates the key if it is new, or replaces the value if it already exists. Reading stock["screws"] returns that integer. If you read a missing key with [], the map inserts it with a default value (0 for int). That surprise is why the next section uses count before you treat a key as present.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> stock;
  stock["nails"] = 40;
  stock["screws"] = 12;
  cout << stock["nails"] << endl;
  cout << stock["screws"] << endl;
  return 0;
}

Output is 40 then 12.

Use Try it in C++ so the program opens at /cpp/try. g++ compiles it in the browser. The Python page at /try will not accept this code.

insert and count

insert adds a pair when the key is new. If the key is already there, insert leaves the old value alone. That differs from [], which overwrites. count(key) returns1 when the key exists and 0 when it does not. A map never stores two copies of the same key, so the answer is never 2.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> stock;
  stock.insert({"bolts", 8});
  stock.insert({"bolts", 99});
  cout << stock["bolts"] << endl;
  cout << stock.count("bolts") << endl;
  cout << stock.count("glue") << endl;
  return 0;
}

Output is 8, then 1, then 0. The second insert did not replace 8 with 99. There is still no "glue" key, so count is 0.

Iterate in key order

A range-for on a map visits each pair. item.first is the key. item.second is the value. std::map keeps keys sorted, so the loop is not “insertion order.” It is sorted order of the keys.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> stock;
  stock["screws"] = 12;
  stock["nails"] = 40;
  stock["bolts"] = 8;
  for (auto item : stock) {
    cout << item.first << " " << item.second << endl;
  }
  return 0;
}

The three lines print as bolts, nails, screws — alphabetical, not the order you assigned. C++17 also lets you writefor (auto [key, value] : stock); first and second are enough here.

String keys, integer values

The pattern is the same for any key type that can be ordered. Strings are the usual choice for names. Integers work as keys too (map<int, string> for an id to a label). This listing tallies votes by candidate name.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> votes;
  votes["Ada"] = 0;
  votes["Linus"] = 0;
  votes["Ada"] = votes["Ada"] + 1;
  votes["Ada"] = votes["Ada"] + 1;
  votes["Linus"] = votes["Linus"] + 1;
  cout << "Ada " << votes["Ada"] << endl;
  cout << "Linus " << votes["Linus"] << endl;
  if (votes.count("Bjarne") == 0) {
    cout << "no Bjarne" << endl;
  }
  return 0;
}

Output is Ada 2, Linus 1, then no Bjarne.

Ordered map

std::map is an ordered map: keys stay sorted, lookup is logarithmic, and a loop is alphabetical (or numeric) by key. If you do not need that order and you want average constant-time lookup, C++ also hasunordered_map in <unordered_map>. This tutorial stays withstd::map.

vectormap
LookupBy index, or scan with findBy key
Order in a loopThe order you pushedSorted by key
Duplicate keysAllowed as duplicate valuesOne entry per key

When a map is the wrong tool

If you only have a list and you always walk it from the front, keep a vector. If you need unique values with no extra payload, a set is the smaller type: just the keys. That is the next chapter.

These listings never open files. They compile with g++ in /cpp/try and on Compiler Explorer.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Chemistry

Atomic number by symbol

Oxygen is 8, carbon is 6. A map looks up the integer from the symbol so you do not scan a list. ["O"] is 8. Missing keys insert 0 if you use []; count() tests first in careful code.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> Z;
  Z["O"] = 8;
  Z["C"] = 6;
  cout << "oxygen Z = " << Z["O"] << endl;
  return 0;
}

Astronomy

Planet year in Earth days

Mars 687, Jupiter 4333. The key is the name; the value is the sidereal period in Earth days. Lookup beats a long if/else chain when the catalogue grows.

Example

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
  map<string, int> year = {{"Mars", 687}, {"Jupiter", 4333}};
  cout << year["Mars"] << " Earth days" << endl;
  return 0;
}

FAQ: C++ Map

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ map examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ map in this C++ C++ lesson (C++ Map).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.