C/C++ Data Structures

Hash Table

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

Hash Table क्या है?

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

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

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

देखें यह कैसे काम करता है

एक key लिखें और उसे सहेजें या खोजें। key को हैश करके बकेट नंबर बनाया जाता है, इसलिए प्रोग्राम सीधे सही बकेट पर पहुँचता है।

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 से तुलना करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज