How to use hash function to create hash table

Muhammad Shafiq 20 Reputation points
2026-11-24T07:30:24.46+00:00

I would like to learn hashing using c++ like, insert, delete, search etc.

Developer technologies | C++
Developer technologies | C++

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.

0 comments No comments

Answer accepted by question author
Taki Ly (WICLOUD CORPORATION) 5,805 Reputation points Microsoft External Staff Moderator
2026-11-24T08:10:23.1533333+00:00

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.

Was this answer helpful?

1 person found this answer helpful.

Answer accepted by question author

AI answer

2026-11-24T07:31:01.16+00:00

Use std::unordered_map<Key, Value> to create a C++ hash table; it applies std::hash<Key> automatically and provides insert, find, and erase for the required operations.^1^

Complete example

#include <iostream>
#include <string>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> students;

    // Insert
    students.insert({101, "Ali"});
    students.emplace(102, "Sara");
    students[103] = "Ahmed";

    // Search
    int key = 102;
    auto it = students.find(key);
    if (it != students.end())
        std::cout << "Found: " << it->second << '\n';
    else
        std::cout << "Not found\n";

    // Delete
    std::cout << "Removed: " << students.erase(101) << '\n';

    // Display remaining entries
    for (const auto& [id, name] : students)
        std::cout << id << ": " << name << '\n';
}

Compile with C++17 or later:

cl /EHsc /std:c++17 main.cpp

How each operation behaves

  • Insert: insert({key, value}) adds the entry only if the key does not already exist. emplace constructs the entry in place.
  • Insert or update: table[key] = value inserts a missing key or replaces the value associated with an existing key. For a missing key, operator[] first creates a default-initialized value.
  • Search: find(key) returns an iterator to the entry, or end() when the key is absent.
  • Delete: erase(key) returns the number of removed entries—normally 1 or 0, because unordered_map has unique keys.^1^
  • Read with bounds checking: at(key) returns the value but throws std::out_of_range if the key is absent.
  • Existence check: With C++20, contains(key) is a simpler Boolean test.

How hashing works

The hash function converts a key into a std::size_t. The container uses that result to select a bucket. Different keys can select the same bucket; this is a collision, and the equality function distinguishes those keys.

When buckets remain reasonably balanced, insertion, search, and deletion can be constant-time on average. If many entries fall into one bucket, an operation can degrade to linear time. The container monitors its load factor and rebuilds its buckets when necessary.^1^

You can inspect the hash and bucket chosen for a key:

auto hash = students.hash_function();
std::cout << "Hash: " << hash(102) << '\n';
std::cout << "Bucket: " << students.bucket(102) << '\n';
std::cout << "Buckets: " << students.bucket_count() << '\n';

Do not depend on iteration order: unordered_map does not guarantee that entries appear in insertion or sorted order.

Custom key and hash function

A custom hash is needed when the key is a user-defined type:

struct StudentKey {
    int school;
    int id;
    bool operator==(const StudentKey& x) const {
        return school == x.school && id == x.id;
    }
};

struct StudentHash {
    std::size_t operator()(const StudentKey& x) const {
        return std::hash<int>{}(x.school)
             ^ (std::hash<int>{}(x.id) << 1);
    }
};

std::unordered_map<StudentKey, std::string, StudentHash> students;

Equal keys must always produce the same hash value. Unequal keys may produce the same hash—the container handles that collision using operator==. The Hash and equality predicate are explicit template parameters of unordered_map.^1^

If only keys are needed, without associated values, use std::unordered_set instead.


References

  1. unordered_map Class
AI-generated content may be incorrect. Read our transparency notes for more information.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.