Adding Key-Value Pairs to an Unordered Map in C++
In C++, an unordered_map is a container that stores elements in key-value pairs, providing fast and efficient lookup operations. If you're working with unordered_map and need to add new key-value pairs, you're at the right place. This guide will walk you through the process in a clear, step-by-step manner.
Understanding Unordered Map
Before we dive into adding key-value pairs, let's quickly recap what an unordered_map is. It's a part of the Standard Template Library (STL) in C++, implemented as a hash table. The 'unordered' part means that the elements are not stored in any specific order, but the 'map' part ensures that each key is unique.
Declaring an Unordered Map
First, you need to declare an unordered_map. Here's a simple example:

std::unordered_map<std::string, int> myMap;
In this case, the keys are strings, and the values are integers.
Adding Key-Value Pairs
Now, let's see how to add key-value pairs to our unordered_map. There are several ways to do this:
Using the Insert Function
The most common way is to use the insert function. Here's how you can add a new pair:

myMap.insert(std::make_pair("key1", 10));
Or, using the since-C++11 uniform initialization syntax:
myMap.insert({"key2", 20});
Using the [] Operator
You can also use the [] operator to add a new pair or modify an existing one:
myMap["key3"] = 30;
If the key "key3" already exists, its value will be updated to 30. If it doesn't, a new pair will be inserted.

Checking for Existing Keys
Before adding a new pair, you might want to check if the key already exists. You can use the find function for this:
if (myMap.find("key1") == myMap.end()) {
myMap["key1"] = 10;
}
In this example, if "key1" doesn't exist, a new pair will be added.
Iterating Over the Unordered Map
After adding key-value pairs, you might want to iterate over the unordered_map to access or modify its elements. Here's how you can do it:
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
Conclusion
In this guide, we've explored how to add key-value pairs to an unordered_map in C++. We've covered different methods, including using the insert function and the [] operator. We've also discussed how to check for existing keys and iterate over the unordered_map. With this knowledge, you're ready to effectively use unordered_map in your C++ projects.





















![Add a Plus Code in Google Maps [How to] - TheAppTimes](https://i.pinimg.com/originals/e4/5a/ce/e45acea7f42a2459b9ed360245cf0ba4.png)
