C++ Insert Key-Value Pairs to an Unordered Map

htt‮sp‬://www.theitroad.com

To insert a key-value pair to an unordered map in C++, you can use the insert() method or the bracket notation.

Here's an example using insert() method:

#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));

    for (auto it = ages.begin(); it != ages.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}

Output:

Michael: 40
John: 30
Emily: 25

Alternatively, you can use the bracket notation to insert key-value pairs:

ages["John"] = 30;
ages["Emily"] = 25;
ages["Michael"] = 40;

Note that if you use the bracket notation to insert a key-value pair with a key that already exists in the map, its value will be overwritten. If you want to avoid this, you can use the insert() method and check if the insertion was successful:

auto result = ages.insert(std::make_pair("John", 35));
if (!result.second) {
    std::cout << "Insertion failed: key already exists." << std::endl;
}