From: Heng Li Date: Mon, 22 Aug 2016 12:31:11 +0000 (-0400) Subject: added one more khash example X-Git-Url: http://www.kaiwu.me/postgresql/commit/static/gitweb.js?a=commitdiff_plain;h=47914bced32b7f5d4842b2e38775e1f2644b19ae;p=klib.git added one more khash example --- diff --git a/index.html b/index.html index 19d6942..4bd920f 100644 --- a/index.html +++ b/index.html @@ -8239,7 +8239,7 @@ pre .xml .cdata {
$:/core/ui/ControlPanel/Appearance
-
+
TableOfContents
@@ -8676,7 +8676,7 @@ int main(int argc, char *argv[]) } ```
-
+
!!Synopsis
 * Functionality: generic hash table with [[open addressing|http://en.wikipedia.org/wiki/Open_addressing]]
 * Library source code: [[khash.h|https://github.com/attractivechaos/klib/blob/master/khash.h]]
@@ -8705,7 +8705,9 @@ int main() {
   return 0;
 }
 ```
-!!!Example 2: counting distinct words (hash table for strings)
+!!!Example 2: counting distinct words (without heap allocation)
+The following demonstrates how to insert string pointers to a hash table, without duplicating keys. If we have string pointers kept elsewhere (in this example, in `argv[]`), this is the preferred way to implement a string hash table.
+
 ```c
 #include <stdio.h>
 #include <string.h>
@@ -8718,21 +8720,43 @@ int main(int argc, char *argv[])
     khint_t k;
     int i, absent;
     h = kh_init(str);
-    for (i = 1; i < argc; ++i) {
+    for (i = 1; i < argc; ++i)
         k = kh_put(str, h, argv[i], &absent);
-        // strdup() is not necessary in this example
-        // we use it to demo hash table deallocation
-        if (absent) kh_key(h, k) = strdup(argv[i]);
-        // else, the key is not touched; we do nothing
-    }
     printf("# of distinct words: %d\n", kh_size(h));
-    // IMPORTANT: free memory allocated by strdup() above
-    for (k = 0; k < kh_end(h); ++k)
-        if (kh_exist(h, k))
-            free((char*)kh_key(h, k));
     kh_destroy(str, h);
     return 0;
 }
+```
+!!!Example 3: coutning distinct words (with heap allocation)
+The following demonstrates how to insert string pointers and their contents into a hash table. This is the //only// approach if the pointers are not kept elsewhere.
+
+```c
+// To run this program: `echo a bc a cd bc|./this_prog`
+#include <stdio.h>
+#include <string.h>
+#include "khash.h"
+KHASH_SET_INIT_STR(str)
+
+int main(int argc, char *argv[])
+{
+	char s[4096]; // max string length: 4095 characters
+	khash_t(str) *h;
+	khint_t k;
+	h = kh_init(str);
+	while (scanf("%s", s) > 0) {
+		int absent;
+		k = kh_put(str, h, s, &absent);
+		if (absent) kh_key(h, k) = strdup(s);
+		// else, the key is not touched; we do nothing
+	}
+	printf("# of distinct words: %d\n", kh_size(h));
+	// IMPORTANT: free memory allocated by strdup() above
+	for (k = 0; k < kh_end(h); ++k)
+		if (kh_exist(h, k))
+			free((char*)kh_key(h, k));
+	kh_destroy(str, h);
+	return 0;
+}
 ```