C++ Access Values of Unordered Maps

http‮‬s://www.theitroad.com

You can access the values of an unordered map in C++ using the square bracket notation or the at() method. Both methods take the key of the value you want to access as an argument.

Here's an example using the square bracket notation:

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> ages;

    ages.insert(std::make_pair("John", 30));
    ages.insert(std::make_pair("Emily", 25));
    ages.insert(std::make_pair("Michael", 40));

    std::cout << "John's age: " << ages["John"] << std::endl;
    std::cout << "Emily's age: " << ages["Emily"] << std::endl;
    std::cout << "Michael's age: " << ages["Michael"] << std::endl;

    return 0;
}

Output:

John's age: 30
Emily's age: 25
Michael's age: 40

Note that if you try to access a key that does not exist in the map using the square bracket notation, a new key-value pair with the default value for the value type will be created. If you want to avoid this behavior, you can use the find() method to check if the key exists before accessing its value:

auto it = ages.find("John");
if (it != ages.end()) {
    std::cout << "John's age: " << it->second << std::endl;
} else {
    std::cout << "John not found in the map." << std::endl;
}

Alternatively, you can use the at() method, which throws an exception if the key is not found in the map:

try {
    std::cout << "John's age: " << ages.at("John") << std::endl;
} catch (const std::out_of_range& e) {
    std::cout << "John not found in the map." << std::endl;
}