unordered_map c++
unordered_map is a container class in C++ that provides a way to store and access elements using key-value pairs. It is part of the Standard Template Library (STL) and is implemented as a hash table.
To use unordered_map in C++, you need to include the
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap;
// Adding elements to the unordered_map
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// Accessing elements using the key
std::cout << "Value at key 2: " << myMap[2] << std::endl;
// Iterating over the unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// Checking if a key exists in the unordered_map
if (myMap.count(3) > 0) {
std::cout << "Key 3 exists!" << std::endl;
}
// Removing an element from the unordered_map
myMap.erase(2);
// Checking the size of the unordered_map
std::cout << "Size of the unordered_map: " << myMap.size() << std::endl;
return 0;
}
In this example, we first include the necessary header files:
We then declare an unordered_map called myMap with key type int and value type std::string.
Next, we add elements to the unordered_map using the key-value pair notation. For example, myMap[1] = "apple" adds the key 1 with the value "apple" to the unordered_map.
We can access elements in the unordered_map using the key. In this example, we print the value at key 2 using myMap[2].
We can iterate over the unordered_map using an iterator. The iterator variable it is used to access the key-value pairs. In the example, we print each key and value using it->first and it->second respectively.
We can check if a key exists in the unordered_map using the count() function. If the count is greater than 0, it means the key exists.
We can remove elements from the unordered_map using the erase() function. In the example, we remove the element with key 2 using myMap.erase(2).
Finally, we can check the size of the unordered_map using the size() function.
That's a basic overview of how to use unordered_map in C++. Let me know if you have any further questions.