Hash tables are a good choice in scenarios where you need fast lookups, insertions, and deletions based on a key. They provide constant-time O(1) average-case complexity for these operations, making them efficient for large datasets.
Consider using hash tables when:
For example, if you're building a phone book application where you want to store and retrieve contact information based on a person's name, a hash table would be a suitable choice. The name can serve as the key, and the associated contact details can be stored as the value.
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<
std::string, std::string> phoneBook;
// Adding entries to the phone book
phoneBook["John"] = "123-456-7890";
phoneBook["Alice"] = "987-654-3210";
// Retrieving a phone number
std::string name = "John";
auto it = phoneBook.find(name);
if (it != phoneBook.end()) {
std::cout << "Phone number of " << name
<< ": " << it->second << '\n';
} else {
std::cout << "Contact not found.\n";
}
}
Phone number of John: 123-456-7890
However, if you need to maintain a sorted order of elements or perform range queries, other data structures like balanced binary search trees (e.g., std::map) might be more appropriate.
Answers to questions are automatically generated and may not have been reviewed.
std::hash
This lesson provides an in-depth look at hashing in C++, including std::hash
, collision strategies, and usage in hash-based containers.