how to change the value of a key in hashmp in c++
To change the value of a key in a C++ unordered_map
, you can follow these steps:
- Access the desired key in the
unordered_map
using the square bracket operator ([]
). - Assign the new value to the key.
Here's an example that demonstrates these steps:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
// Insert some key-value pairs
myMap["apple"] = 5;
myMap["banana"] = 10;
myMap["orange"] = 15;
// Print the initial values
std::cout << "Initial values:" << std::endl;
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// Change the value of the "banana" key
myMap["banana"] = 20;
// Print the updated values
std::cout << "Updated values:" << std::endl;
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
Output:
Initial values:
orange: 15
banana: 10
apple: 5
Updated values:
orange: 15
banana: 20
apple: 5
In this example, we first create an unordered_map
called myMap
that maps strings to integers. We insert three key-value pairs into myMap
. Then, we iterate over the map and print the initial values.
To change the value of the "banana" key, we use the square bracket operator myMap["banana"]
and assign a new value of 20 to it. Finally, we iterate over the map again and print the updated values.
You can replace the types std::string
and int
with your desired key and value types in the actual code.