C/C++ Data Structures

Hash Table

Hash function key को bucket में map करता है; collision के लिए strategy चाहिए।

Hash Table क्या है?

Hash function key को bucket में map करता है; collision के लिए strategy चाहिए।

Chaining और unordered_map से words गिनें।

महत्वपूर्ण बातें

  • Operations से पहले invariants तय करें।
  • Empty, full और allocation-failure cases संभालें।
  • Complexity और ownership साथ मापें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>
#include <string.h>

typedef struct Item {
    const char *key;
    int count;
    struct Item *next;
} Item;

unsigned hash(const char *text) {
    unsigned value = 5381;
    while (*text) {
        value = value * 33u ^ (unsigned char)*text++;
    }
    return value % 5;
}

int main(void) {
    const char *words[] = {"c", "cpp", "c"};
    Item items[2] = {{"c", 0, NULL}, {"cpp", 0, NULL}};
    Item *buckets[5] = {0};

    for (int index = 0; index < 2; ++index) {
        unsigned bucket = hash(items[index].key);
        items[index].next = buckets[bucket];
        buckets[bucket] = &items[index];
    }
    for (int index = 0; index < 3; ++index) {
        Item *item = buckets[hash(words[index])];
        for (; item; item = item->next) {
            if (strcmp(item->key, words[index]) == 0) {
                ++item->count;
                break;
            }
        }
    }
    printf("c=%d cpp=%d\n", items[0].count, items[1].count);
}
अपेक्षित output
c=2 cpp=1
C++
कोड चलाएँ →
main.cpp
#include <iostream>
#include <string>
#include <unordered_map>

int main() {
    std::unordered_map<std::string, int> counts;
    for (const std::string word : {"c", "cpp", "c"}) {
        ++counts[word];
    }
    std::cout << "c=" << counts["c"]
              << " cpp=" << counts["cpp"] << '\n';
}
अपेक्षित output
c=2 cpp=1

C और C++ की तुलना

C example buckets समझाने को fixed keys रखता है; std::unordered_map nodes own, auto-grow और arbitrary strings संभालता है।

C

Structures और operations अलग, allocation स्पष्ट होता है।

C++

Classes और containers invariants और resources manage करते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Empty और capacity boundary tests जोड़ें।
  • Cleanup लागू कर leaks जाँचें।
  • Standard container से तुलना करें।