put
Coddyの「ハッシュテーブル - データ構造シリーズ #4」コースのレッスン 5/14。
チャレンジ
簡単HashMap クラスに put メソッドを追加してください。
このメソッドは整数の key と整数の value を受け取り、そのペアをテーブルに格納します。
- キーが既に存在する場合は、その値を更新します。
- 存在しない場合は、適切なバケットに新しい
[key, value]ペアを追加し、countをインクリメントします。
自分で試してみよう
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashmap.h"
int main() {
HashMap h;
HashMap_init(&h);
char line[256];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "state") == 0) { printf("%d %d %d\n", h.capacity, h.capacity, h.count); }
if (strcmp(cmd, "hash") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", HashMap_hash(&h, atoi(arg))); }
if (strcmp(cmd, "put") == 0) { char* a = strtok(NULL, " \t"); char* b = strtok(NULL, " \t"); if (a && b) HashMap_put(&h, atoi(a), atoi(b)); }
if (strcmp(cmd, "bucketSize") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", h.buckets[atoi(arg)].size); }
if (strcmp(cmd, "count") == 0) { printf("%d\n", h.count); }
}
return 0;
}