Skip to content

Instantly share code, notes, and snippets.

@brentp
Created December 31, 2013 23:13
Show Gist options
  • Save brentp/8203231 to your computer and use it in GitHub Desktop.
Save brentp/8203231 to your computer and use it in GitHub Desktop.
/*
* example for me to learn khash.h library from lh3
*/
#include "khash.h"
#include <stdio.h>
// int keys and char * values
KHASH_MAP_INIT_INT(ihash, char *)
// char * keys and char * values
KHASH_MAP_INIT_STR(chash, char *)
char *strings[3] = {"aa", "bb", "cc"};
int main() {
int ret, is_missing, i;
khiter_t key;
// define a new ihash h
khash_t(ihash) *h = kh_init(ihash);
char *val;
for(i=0; i < 3, val=strings[i]; i++){
// put the key of 5 into the hash
key = kh_put(ihash, h, i, &ret);
// give it a value
kh_val(h, key) = val;
}
// make sure it's in there.
for(i = 0; i < 5; i++){
key = kh_get(ihash, h, i);
// get the value of each key if it's present.
if (key != kh_end(h)){
printf("value at %d: %s\n", i, kh_val(h, key));
} else {
printf("%d missing\n", i);
}
}
// delete a key and make sure it's gone
kh_del(ihash, h, 1);
key = kh_get(ihash, h, 1);
printf("should be 1:%d\n", key == kh_end(h));
kh_destroy(ihash, h);
printf("char * => char *\n");
// now with another type of hash
khash_t(chash) *hc = kh_init(chash);
key = kh_put(chash, hc, "akey", &ret);
kh_val(hc, key) = "aval";
key = kh_get(chash, hc, "akey");
printf("value at akey: %s\n", kh_val(hc, key));
kh_destroy(chash, hc);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment