Imagine you have a huge phone book and you want to find a person's phone number quickly. Which problem does a hash map help solve?
Think about how long it takes to find a name in a phone book if you check every name one by one.
A hash map allows quick access to data by using a key to find the exact location, avoiding slow searches through all data.
What is the output of the following C++ code that uses a hash map (unordered_map)?
std::unordered_map<std::string, int> map; map["apple"] = 5; map["banana"] = 3; map["apple"] = 7; for (auto &pair : map) { std::cout << pair.first << ":" << pair.second << " "; }
Remember that inserting with the same key updates the value. The order of elements in unordered_map is not guaranteed.
The value for "apple" is updated to 7. The order of printing is not fixed, so banana may appear before apple.
Consider this C++ code snippet:
std::unordered_mapmap; int value = map.at(10);
What error will this code cause and why?
Check what happens when you try to access a key that is not present using 'at'.
The 'at' method throws an out_of_range exception if the key is missing. It does not insert or return a default value.
What is the output of this C++ code that counts characters in a string?
std::string s = "hello"; std::unordered_map<char, int> count; for (char c : s) { count[c]++; } for (auto &p : count) { std::cout << p.first << ":" << p.second << " "; }
Count how many times each letter appears in "hello".
The letter 'l' appears twice, others once. The order is not guaranteed but counts are correct.
Which reason best explains why hash maps provide faster lookup than lists?
Think about how a hash function helps find data quickly.
Hash maps use a hash function to compute an index, allowing direct access instead of scanning elements one by one.
