C/C++のデータ構造

Hash Table

Hash functionがkeyをbucketへ割り当て、collisionには解決方法が必要です。

Hash Tableとは?

Hash functionがkeyをbucketへ割り当て、collisionには解決方法が必要です。

Chainingとunordered_mapで単語を数えます。

重要なポイント

  • 操作より先にinvariantを定義します。
  • 空・満杯・allocation失敗を処理します。
  • 計算量と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例はbucket理解のためkeyを固定します。std::unordered_mapはnodeを所有し自動成長し任意のstringを扱います。

C

構造体と操作は分離され、allocationは明示的です。

C++

classとcontainerがinvariantとresourceを管理します。

練習課題

両方を実行して変更し、言語ごとの保証を確認します。

  • 空と容量境界をテストします。
  • cleanupを実装しleakを確認します。
  • standard containerと比較します。