C++ Change Values of an Unordered Map
You can change the value associated with a key in 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 change 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 << "Before changing values:" << std::endl; 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; ages["John"] = 35; ages["Emily"] = 30; ages["Michael"] = 45; std::cout << "After changing values:" << std::endl; 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; }Source:i.wwwgiftidea.com
Output:
Before changing values: John's age: 30 Emily's age: 25 Michael's age: 40 After changing values: John's age: 35 Emily's age: 30 Michael's age: 45
Note that if you try to change the value of a key that does not exist in the map using the square bracket notation, a new key-value pair with the new value will be created. If you want to avoid this behavior, you can use the find()
method to check if the key exists before changing its value:
auto it = ages.find("John"); if (it != ages.end()) { it->second = 35; } 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 { ages.at("John") = 35; } catch (const std::out_of_range& e) { std::cout << "John not found in the map." << std::endl; }