-
-
Save reterVision/de4e3998c9ec1c9512ce to your computer and use it in GitHub Desktop.
Simple Hash map without solving the collision.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| class Hash | |
| { | |
| public: | |
| Hash() {}; | |
| ~Hash() {}; | |
| void add(string key, string value); | |
| void remove(string key, string value); | |
| string get(string key); | |
| long calc_hash(string key); | |
| protected: | |
| string pool[100]; | |
| }; | |
| long Hash::calc_hash(string key) | |
| { | |
| long hash = 5381; | |
| for (int i=0; i<key.length(); i++) { | |
| hash = ((hash << 5) + hash) + key[i]; | |
| } | |
| hash %= 100; | |
| return hash; | |
| } | |
| void Hash::add(string key, string value) | |
| { | |
| long hash = calc_hash(key); | |
| if (pool[hash].empty()) { | |
| pool[hash] = value; | |
| } | |
| } | |
| void Hash::remove(string key, string value) | |
| { | |
| long hash = calc_hash(key); | |
| if (!pool[hash].empty()) { | |
| pool[hash].clear(); | |
| } | |
| } | |
| string Hash::get(string key) | |
| { | |
| long hash = calc_hash(key); | |
| return pool[hash]; | |
| } | |
| int main(int argc, char* argv[]) | |
| { | |
| Hash hash; | |
| hash.add("hello", "world"); | |
| cout << hash.get("hello") << endl; | |
| hash.add("nihao", "hej, hej"); | |
| cout << hash.get("nihao") << endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment