Start learning free

LESSON 122 OF 667 · DICTIONARIES

Accessing Dictionary Values in C++

Lesson

In C++, you access values in an unordered_map using square bracket notation or at():

unordered_map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;

int aliceScore = scores["Alice"];  // 95
int bobScore = scores.at("Bob");   // 87

Note: scores["key"] inserts a default value (0) if the key doesn't exist. Use at() to get an exception instead, or count() to check existence:

if (scores.count("Alice") > 0) {
    cout << scores["Alice"];
}

Assignment
Follow the Coding Tutorial and access Alice's score from scores!


Hint
Use scores["Alice"] and assign it to aliceScore.

STEP 1 OF 1
    Ctrl + Enter to check