dynamic hashset in C

13,315

Solution 1

I would recommend (as always) the nice GLib (part of GTK+). It has the GHashTable API which implements a hash table. It grows dynamically as needed.

To use 32-bit keys, reference the g_int_hash() and g_int_equal() functions when creating your hash table.

Solution 2

UPDATE: DO NOT USE THIS LIBRARY FOR STRINGS!
See this ticket for more info: https://github.com/avsej/hashset.c/issues/4

The HashSet code from Couchbase seems nice:

https://github.com/avsej/hashset.c

Example:

#include "hashset.h"

char *foo = "foo";
char *missing = "missing";
hashset_t set = hashset_create();

if (set == NULL) {
    fprintf(stderr, "failed to create hashset instance\n");
    abort();
}

hashset_add(set, foo);
assert(hashset_is_member(set, foo) == 1);
assert(hashset_is_member(set, missing) == 0);

Solution 3

I successfully use this one: KoanLogic Libu - Hmap module

The example in the link is enough self explaining. For your needs i guess you should use U_HMAP_OPTS_DATATYPE_OPAQUE as datatype and set the length of your key to 4 bytes with u_hmap_opts_set_val_sz().

Share:
13,315

Related videos on Youtube

reox
Author by

reox

Just another PhD Student

Updated on September 15, 2022

Comments

  • reox
    reox almost 2 years

    i need some kind of HashSet in C which can dynamicly grow in size. I could of course write everything on my own but maybe there is a good lib for that? My Keys are 32bit hashes and i need to save a pointer (struct dirent *) as value.

  • Ray Hulha
    Ray Hulha almost 9 years
    I take it back, the library seems not well suited for string handling: It hashes based on the pointer address in memory...
  • Johann Gerell
    Johann Gerell almost 9 years
    Upped for the due diligence - I'd hate to choose that hashset and discover too late what you just did :)
  • Ray Hulha
    Ray Hulha almost 9 years
    @JohannGerell Thanks mate :-) Yeah it bit me in the butt yesterday... :-( I even think it is ill suited for anything... It hashes based on the memory address... How is that useful for anything a bit more complex ? I can't believe it is used in couchbase...