c ++ program to insert into hashmap
Sure! Here is an example of a C++ program that inserts key-value pairs into a hashmap, along with explanations for each step:
#include <iostream>
#include <unordered_map>
int main() {
// Step 1: Create an empty hashmap
std::unordered_map<int, std::string> hashmap;
// Step 2: Insert key-value pairs into the hashmap
hashmap.insert(std::make_pair(1, "Apple"));
hashmap.insert(std::make_pair(2, "Banana"));
hashmap.insert(std::make_pair(3, "Orange"));
// Step 3: Access and print the values associated with the keys
std::cout << "Value at key 1: " << hashmap[1] << std::endl;
std::cout << "Value at key 2: " << hashmap[2] << std::endl;
std::cout << "Value at key 3: " << hashmap[3] << std::endl;
return 0;
}
Explanation for each step:
Step 1: We create an empty hashmap by declaring a variable of type
std::unordered_map<int, std::string>
. This hashmap will store integer keys and string values. You can change the types of the key and value to suit your requirements.Step 2: We insert key-value pairs into the hashmap using the
insert
function. In this example, we use thestd::make_pair
function to create pairs and pass them to theinsert
function. You can insert as many key-value pairs as needed.Step 3: We access and print the values associated with the keys in the hashmap using the subscript operator
[]
. In this example, we access the values associated with keys 1, 2, and 3, and print them to the console. You can access values for any key present in the hashmap.Finally, the program ends by returning 0 from the
main
function, indicating successful execution.
I hope this example helps! Let me know if you have any further questions.