A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Hi @Muhammad Shafiq ,
Since you want to learn how hashing works, it helps to build a small hash table yourself. The hash function turns a key into a number, and that number modulo the bucket count tells you which bucket the key goes in. When two keys land in the same bucket (a collision), each bucket can simply keep a list of its entries. This approach is called separate chaining. In C++ you can use std::hash as the hash function. The hash Class documentation describes it as a function object "suitable for mapping values of type Ty to a distribution of index values."
Below is the core idea:
std::vector<std::list<std::pair<std::string, int>>> buckets(8);
std::size_t indexFor(const std::string& key) {
return std::hash<std::string>{}(key) % buckets.size();
}
void insert(const std::string& key, int value) {
auto& bucket = buckets[indexFor(key)];
for (auto& entry : bucket)
if (entry.first == key) { entry.second = value; return; }
bucket.emplace_back(key, value);
}
int* search(const std::string& key) {
for (auto& entry : buckets[indexFor(key)])
if (entry.first == key) return &entry.second;
return nullptr;
}
bool remove(const std::string& key) {
auto& bucket = buckets[indexFor(key)];
for (auto it = bucket.begin(); it != bucket.end(); ++it)
if (it->first == key) { bucket.erase(it); return true; }
return false;
}
All three operations hash the key first and then scan only one bucket, not the whole table. That's why hash tables are fast on average. If many keys end up in the same bucket, operations get slower, so a full implementation usually adds more buckets (rehashes) as the table fills.
For real projects, I would suggest std::unordered_map, which implements the same concept. The unordered_map Class documentation notes that operations are constant time "at least when all buckets are of roughly equal length."
I hope this helps. Please let me know if you have any further questions. If my response was helpful or informative, I'd really appreciate it if you could follow this guide so that others with the same question can benefit.
Thank you.