Loading...

C++ map

The vector-methods page left one line on the screen in box.cpp: 1, after words.push_back("pine"); and printing words.size(). This page stays in the Memory and Collections module on purpose. The workshop file on disk stays box.cpp so you keep one familiar build path. The new work stores a value under a string key in a map, then prints the value for key pine. The screen shows one line: 1.
A map holds pairs of keys and values. On this page you write std::map<std::string, int> counts; and then counts["pine"] = 1;. The first type in the angle brackets is the key type. The second type is the value type. Then std::cout << counts["pine"] << std::endl; prints the int stored under the key pine. Reading counts["pine"] = 1 is reading a store under that key. Reading counts["pine"] on the print line is reading that stored value back out.
Programs use map when you look up a value by a key instead of by a list index. You do not keep the vector and size path as the lesson body on this page, even though both tools live in the same module. Extra containers like set wait for the next page on purpose. Here the point is only creating the map, storing 1 under pine, and printing that value. The build command stays familiar: one source file box.cpp, one output name box, one run that prints 1. Keep #include <iostream>, #include <string>, and #include <map> together at the top. You compile only box.cpp again for this workshop file on disk.
Think of the key pine as a label on a shelf. After counts["pine"] = 1;, that shelf holds the number 1. Printing counts["pine"] reads the shelf and shows 1. The previous pages already used the word pine in a list. This page uses pine as a key instead of as a list item. The screen line is still the digit 1, but now that digit comes from a map lookup, not from size().

Inside main, write std::map<std::string, int> counts;, then counts["pine"] = 1;, then std::cout << counts["pine"] << std::endl;, then return 0;. Keep the three includes at the top of the file. Do not print through a vector on this page. Do not leave the map empty and still expect a meaningful value under pine.
Walk the run carefully from the first line of main. The program starts at main. counts starts empty with no keys yet. counts["pine"] = 1 stores the value 1 under the key pine. Printing counts["pine"] shows 1 on the screen. Then main returns and the program ends. There is one line on the screen. It is 1, not pine. The key pine is the label; the printed value is the int. The checked file always stores under pine before it prints that key.
Say the steps out loud once while you read the file. Empty map. Store 1 under pine. Print the value for pine. Return. That short story is the whole workshop path. Nothing else belongs in the checked body. No second key. No vector include. No extra include beyond the three you already keep. When the screen shows 1, the story matched the source.

If you print counts["pine"] before any store under that key, the map can create a default int of 0 for that key. That experiment can stay in the prose. The checked file always stores 1 under pine first so the screen is 1.
If you forget #include <map>, the build fails about std::map. The checked file keeps that include next to iostream and string.
A common mistake is to keep the old vector body and never add the map. Another common mistake is to print the key string pine instead of the value under it. A third mistake is to use the wrong key and read a different entry. A fourth mistake is to print a literal 1 and never use the map. A fifth mistake is to drop #include <string> while using std::string as the key type.
This page stops before the next tool, where a set stores unique values. The next page names that tool once at the end. The map you have just written only shows one store and one print by key in the same function. Keep the store before the print so the order stays clear for a first careful reading of the file.
Remember that assigning under pine does not print by itself. You still write the std::cout line. After one store the printed value is 1. After you undo an oak experiment the checked file returns to pine alone. After you restore the checked print line the screen returns to that same single digit. Stability of the checked file matters as much as learning the map itself.

Open box.cpp. Remove the vector lines from the vector-methods demo. Add #include <map> beside the other includes and drop #include <vector>. In main, create counts, store counts["pine"] = 1;, and print counts["pine"] as the only screen line. The file name on disk stays box.cpp. The checked file is below, and the new lines are the map type, the store under pine, and the lookup print.

box.cpp stores 1 under key pine and prints it

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

int main()
{
    std::map<std::string, int> counts;
    counts["pine"] = 1;
    std::cout << counts["pine"] << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 box.cpp -o box, then run ./box. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 box.cpp -o box. The screen shows one line: 1.
Check that line first on the screen. The map held 1 under pine after the store, so the print showed 1. The table gives each row its piece, so compare your run with it line by line before you move on to experiments. If the screen shows 0, the store under pine may be missing. If the screen shows pine, you printed the key string instead of the value. If the build fails about map, check #include <map>.

📊 map and what the screen shows

Piece What the screen shows
First 1, because counts["pine"] = 1 stored that value before the print
Last 1, because the program prints one line and stops
Rule a map stores values under keys; counts["pine"] reads the value for pine
Screen 1

Try one change at a time. Change the stored value to counts["pine"] = 2;, leave the print as counts["pine"], and rebuild. The screen shows 2 instead of 1, because only the value under pine changed. Restore = 1. Next, temporarily add counts["oak"] = 3; and print counts["oak"] instead, then rebuild to see 3. Undo that so the file returns to one key pine with value 1. Each experiment changes one thing on purpose, so the screen shows which key and value you chose. Undo each change before the next one starts, so the file always returns to the checked workshop version with counts["pine"] = 1; and counts["pine"] printed once again after every single careful try back on disk again.
This page ends the map tool and stops before the next one. The next page is set, which stores unique values without key pairs. The map you have just written only shows storing 1 under pine in box.cpp. You leave with one line on the screen: 1. Count the lines before you leave. There is exactly one printed line on that final screen, and that single printed line on the screen is still just 1 alone right there now after the final successful build run on disk today now after the map lookup.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top