gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
syntax of hashmap of int int in c++
- User
syntax of hashmap of int int in c++
- Assistant
In C++, you can use the
std::unordered_mapfrom the C++ Standard Library to create a hash map (or hash table) that maps integers to integers. Here is the syntax for declaring and using a hash map that mapsintkeys tointvalues:#include <iostream> #include <unordered_map> int main() { // Declare a hash map (unordered_map) for int-int pairs std::unordered_map<int, int> hashMap; // Inserting elements into the hash map hashMap[1] = 100; // Key 1 maps to value 100 hashMap[2] = 200; // Key 2 maps to value 200 hashMap[3] = 300; // Key 3 maps to value 300 // Accessing values using keys std::cout << "Value for key 1: " << hashMap[1] << std::endl; // Outputs 100 std::cout << "Value for key 2: " << hashMap[2] << std::endl; // Outputs 200 // Iterating over the hash map for (const auto& pair : hashMap) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; } // Checking if a key exists int keyToCheck = 3; if (hashMap.find(keyToCheck) != hashMap.end()) { std::cout << "Key " << keyToCheck << " exists with value: " << hashMap[keyToCheck] << std::endl; } else { std::cout << "Key " << keyToCheck << " does not exist." << std::endl; } return 0; }