哈希表:冲突、负键和删除
平均常数依赖负载与散列质量。
逐步查看固定输入下的数据变化。这里回放本地C程序的实际结果;下载源码后可修改输入并重新编译。
实际运行范围
当前固定输入有 35 项断言通过。本次实验创建的动态节点已全部释放。当前结果对应本章固定输入,改变输入后请重新编译核对。
编译器:Zig 0.14.1 cc;标准:C11;本轮环境:Windows。
编译:zig cc -std=c11 -Wall -Wextra -Werror -pedantic c-dsa-hash-table.c dsa.c -o demo.exe,再运行demo.exe。
本章完整入口
#include "test_support.h"
int main(void){
puts("MBSKY | mbsky.com | independently authored C11 case");
Hash h={0};int out;CHECK(hash_put(&h,1,100));CHECK(hash_put(&h,11,300));CHECK(hash_put(&h,-9,-1));CHECK(hash_get(&h,1,&out)&&out==100);CHECK(hash_get(&h,11,&out)&&out==300);CHECK(hash_get(&h,-9,&out)&&out==-1);CHECK(!hash_get(&h,99,&out));CHECK(hash_put(&h,1,999));CHECK(hash_get(&h,1,&out)&&out==999);state("collision-keys",(int[]){1,11,-9},3);state("collision-values",(int[]){999,300,-1},3);CHECK(hash_delete(&h,11));CHECK(!hash_get(&h,11,&out));CHECK(hash_get(&h,1,&out)&&out==999);allocation_fail_after(0);CHECK(!hash_put(&h,21,4));allocation_fail_after(-1);hash_clear(&h);OpenHash o={0};CHECK(open_put(&o,1,10));CHECK(open_put(&o,11,20));CHECK(open_put(&o,21,30));CHECK(open_delete(&o,11));CHECK(open_get(&o,21,&out)&&out==30);CHECK(open_put(&o,31,40));CHECK(open_get(&o,31,&out)&&out==40);CHECK(open_put(&o,21,33));CHECK(open_get(&o,21,&out)&&out==33);state("tombstone-reuse",(int[]){o.state[1],o.state[2],o.state[3]},3);OpenHash full={0};for(int i=0;i<BUCKETS;++i)CHECK(open_put(&full,i,i));CHECK(!open_put(&full,101,7));CHECK(!open_get(&full,111,&out));
return finish();
}