From 33278ed54578b3e110f22f8e97a3687a81df811e Mon Sep 17 00:00:00 2001 From: Cotton Seed Date: Thu, 29 Dec 2011 11:51:58 -0500 Subject: [PATCH] Added hash and comparisons for std::string. --- lib/lib.cpp | 10 ++++++++++ lib/lib.h | 17 +++++++++++++++++ main.cpp | 20 +++++++++++++++++++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/lib/lib.cpp b/lib/lib.cpp index 74ff094..45f700c 100644 --- a/lib/lib.cpp +++ b/lib/lib.cpp @@ -72,3 +72,13 @@ alpha_to_int (char c) return - (c - 'A' + 1); } } + +hash_t +hash (const std::string &s) +{ + size_t n = s.length (); + hash_t h = hash (n); + for (unsigned i = 0; i < n; i ++) + h = hash_combine (h, hash (s[i])); + return h; +} diff --git a/lib/lib.h b/lib/lib.h index 3c97fbf..e72b113 100644 --- a/lib/lib.h +++ b/lib/lib.h @@ -47,6 +47,23 @@ inline hash_t hash (unsigned long x) { return (hash_t)x; } inline hash_t hash (uint64 x) { return (hash_t)((x >> 32) ^ x); } +hash_t hash (const std::string &s); + +inline bool operator == (const std::string &s, const std::string &t) +{ + return strcmp (s.c_str (), t.c_str ()) == 0; +} + +inline bool operator < (const std::string &s, const std::string &t) +{ + return strcmp (s.c_str (), t.c_str ()) < 0; +} + +inline bool operator <= (const std::string &s, const std::string &t) +{ + return strcmp (s.c_str (), t.c_str ()) <= 0; +} + template inline hash_t hash (const T &x) { diff --git a/main.cpp b/main.cpp index 7aec9c6..5c7a627 100644 --- a/main.cpp +++ b/main.cpp @@ -143,7 +143,25 @@ main () } #endif -#if 1 + map m; + m.push ("foo", 3); + m.push ("barz", 4); + m.push ("pazazz", 39); + + assert (m % "foo"); + assert (m("foo") == 3); + assert (! (m % "fop")); + + hashmap m2; + m2.push ("foo", 3); + m2.push ("barz", 4); + m2.push ("pazazz", 39); + + assert (m2 % "foo"); + assert (m2("foo") == 3); + assert (! (m2 % "fop")); + +#if 0 test_ring (2); test_ring (0); test_ring (0);