Associative arrays/Creation/C: Difference between revisions
loop
(→From Scratch: remove hash_free function) |
(loop) |
||
(4 intermediate revisions by 2 users not shown) | |||
Line 2:
* Back to [[Associative arrays/Creation]].
==From Scratch==
A hash table can be implemented with the following. Because of this example's simplicity, it comes with some restrictions on use and capabilities: It can't be resized automatically, if you try to insert more values than its capacity it will freeze, the hashing function is very simple, etc. All are fixable with additional logic or using a library:
<syntaxhighlight lang="с">
<lang c>typedef struct {▼
#include <stdlib.h>
int size;
void **keys;
void **values;
}
return
}
int hash_index (
int
while (
return
}
void hash_insert (
int
}
void *hash_lookup (
int
return
}
int main () {
hash_insert(
hash_insert(
printf("hello => %s\n", hash_lookup(
printf("herp => %s\n", hash_lookup(
printf("a => %s\n", hash_lookup(
return 0;
}
</syntaxhighlight>
==Libraries==
Line 55 ⟶ 59:
{{libheader|Judy}}
<syntaxhighlight lang="с">
▲<lang c>#include <stdio.h>
#include <stdio.h>
#include <Judy.h>
Line 88 ⟶ 93:
return 0;
}
</syntaxhighlight>
{{libheader|Judy}}
Line 94 ⟶ 100:
We can easily iterate over pair of keys (indexes) and values.
<
#include <Judy.h>
Line 125 ⟶ 131:
JudySLFreeArray(&assoc_arr, PJE0);
return 0;
}</
===POSIX hsearch()===
Line 147 ⟶ 153:
{{libheader|POSIX}}
<
#include <search.h> /* hcreate(), hsearch() */
#include <stdio.h> /* perror(), printf() */
Line 238 ⟶ 244:
*/
return 0;
}</
<pre>red has value ff0000
Line 250 ⟶ 256:
====To delete or iterate====
{{libheader|POSIX}}
<
#include <search.h>
#include <stdio.h>
Line 399 ⟶ 405:
return 0;
}</
<pre>5 is not deleted
Line 426 ⟶ 432:
{{works with|OpenBSD|4.8}}
<
#include <err.h> /* err() */
Line 651 ⟶ 657:
number_example();
return 0;
}</
Output:
Line 674 ⟶ 680:
{{works with|OpenBSD|4.8}}
<
#include <err.h> /* err() */
Line 896 ⟶ 902:
number_example();
return 0;
}</
Output:
|