Skip to content

Instantly share code, notes, and snippets.

@reterVision
Created January 11, 2014 12:24
Show Gist options
  • Save reterVision/de4e3998c9ec1c9512ce to your computer and use it in GitHub Desktop.
Save reterVision/de4e3998c9ec1c9512ce to your computer and use it in GitHub Desktop.
Simple Hash map without solving the collision.
#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