c ++ program to search hashmap
Here is an example of a C++ program that searches a hashmap:
#include <iostream>
#include <unordered_map>
int main() {
// Create a hashmap
std::unordered_map<int, std::string> hashmap;
// Add some key-value pairs to the hashmap
hashmap[1] = "apple";
hashmap[2] = "banana";
hashmap[3] = "orange";
// Search for a key in the hashmap
int key = 2;
auto it = hashmap.find(key);
// Check if the key was found
if (it != hashmap.end()) {
std::cout << "Key " << key << " found. Value: " << it->second << std::endl;
} else {
std::cout << "Key " << key << " not found." << std::endl;
}
return 0;
}
Let's go through the steps of this program:
Include necessary headers: The program starts by including the necessary headers. In this case, we include
<iostream>
for input/output operations and<unordered_map>
for using the unordered_map container.Create a hashmap: We declare an unordered_map named
hashmap
to store key-value pairs. In this example, the keys are integers and the values are strings.Add key-value pairs: We add some key-value pairs to the hashmap using the square bracket notation. For example,
hashmap[1] = "apple";
adds the key-value pair of 1 and "apple" to the hashmap.Search for a key: We define a key to search for in the hashmap. In this example, the key is 2.
Find the key in the hashmap: We use the
find()
function of the hashmap to search for the specified key. Thefind()
function returns an iterator pointing to the found element, orhashmap.end()
if the element is not found.Check if the key was found: We check if the iterator returned by
find()
is equal tohashmap.end()
. If it is not equal, it means the key was found in the hashmap.Print the result: If the key is found, we print the key and its corresponding value using the iterator. Otherwise, we print a message indicating that the key was not found.
Return 0: Finally, the program returns 0 to indicate successful execution.
This program demonstrates how to create and search a hashmap in C++. You can modify it to suit your specific needs by changing the key and value types or adding more key-value pairs to the hashmap.