4 ms·
Key collisions are of course a problem. This is a quick and dirty implementation. If you care about checking for collisions, you could instead have: typede
by bArray 4y ago
Key collisions are of course a problem. This is a quick and dirty implementation. If you care about checking for collisions, you could instead have:
typedef struct{ char* k; char* v; } KV;
int L = <table length>; // Large enough to reduce collisions
KV* t = (KV*)malloc(L * sizeof(KV));
memset(t, 0, L * sizeof(KV)); // Set it all to empty by default
Then:
/* Put example (detect collisions) */
char* k;
if(t[H(k) % L] == NULL || strcmp(t[H(k) % L].k, k) == 0)
t[H(k) % L] = "value string";
else
printf("Collision\n"); // Handle as you like
Of course this can get more and more advanced. The point wasn't to make a zero-collision table, it was just something that could be used quickly.
- anonymoushn 4y agoThe point of the replies to your original comment is that it can't be used for most purposes, and writing all the code to make it usable results in something similar to the implementation in the article.
- bArray 4y agoHence why I wrote "For an ultra simple hash table". I think that for C that doesn't natively have such a data structure, a couple of lines to introduce such a structure really isn't too bad.
- zbird 4y agoIt's not clear what 'ultra simple' means. Could have just said that it doesn't handle collisions. And I think for most cases, you do want to handle collisions.