Revision: 425
http://assorted.svn.sourceforge.net/assorted/?rev=425&view=rev
Author: yangzhang
Date: 2008-02-14 18:28:31 -0800 (Thu, 14 Feb 2008)
Log Message:
-----------
added demo of using hash maps for strings
Added Paths:
-----------
sandbox/trunk/src/cc/hash_map_strings.cc
Added: sandbox/trunk/src/cc/hash_map_strings.cc
===================================================================
--- sandbox/trunk/src/cc/hash_map_strings.cc (rev 0)
+++ sandbox/trunk/src/cc/hash_map_strings.cc 2008-02-15 02:28:31 UTC (rev 425)
@@ -0,0 +1,52 @@
+#include <iostream>
+#include <string>
+
+// #include <ext/hash_fun.h>
+#include <ext/hash_map>
+#include <ext/hash_set>
+
+using namespace std;
+using namespace __gnu_cxx;
+
+struct eqstr
+{
+ bool operator()(const char* s1, const char* s2) const
+ {
+ return strcmp(s1, s2) == 0;
+ }
+};
+
+int
+main()
+{
+ {
+ // This doesn't compile because there is no hash function for strings.
+ // string s = "hello, world!";
+ // hash_set<string> h;
+ // h.insert(s);
+ }
+
+ {
+ // The two other arguments are required. Note that eqstr is custom-defined
+ // above.
+ hash_set< const char *, hash<const char*>, eqstr > h;
+
+ const char *s = "hello, world!";
+ h.insert(s);
+
+ const int nss = 20;
+ char *ss[nss];
+ // Duplicate s nss times into ss and h.
+ for (int i = 0; i < nss; i++) {
+ ss[i] = new char[strlen(s) + 1];
+ strcpy(ss[i], s);
+ cout << ss[i] << endl;
+ h.insert(ss[i]);
+ }
+
+ // This prints 1, which is what we want.
+ cout << h.size() << endl;
+ }
+
+ return 0;
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|