โครงสร้างข้อมูลใน C/C++

Hash Table

Hash function map key ไป bucket และ collision ต้องมีวิธีจัดการ

Hash Table คืออะไร?

Hash function map key ไป bucket และ collision ต้องมีวิธีจัดการ

นับคำด้วย chaining และ unordered_map

ประเด็นสำคัญ

  • กำหนด invariant ก่อนเขียน operation
  • จัดการกรณีว่าง เต็ม และ allocation ล้มเหลว
  • ประเมิน complexity และ ownership พร้อมกัน

ตัวอย่างโค้ด C และ C++

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);
}
ผลลัพธ์ที่คาดหวัง
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';
}
ผลลัพธ์ที่คาดหวัง
c=2 cpp=1

เปรียบเทียบ C และ C++

ตัวอย่าง C ใช้ key คงที่เพื่อสอน bucket ส่วน std::unordered_map เป็นเจ้าของ node เติบโตเองและรับ string ทั่วไป

C

Struct และ operation แยกกัน การจัดสรรชัดเจน

C++

Class และ container รักษา invariant และ resource

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • ทดสอบสถานะว่างและเต็ม
  • เขียน cleanup และตรวจ memory leak
  • เปรียบเทียบกับ standard container