Skip to content

Instantly share code, notes, and snippets.

@sat0b
Last active October 22, 2017 15:21
Show Gist options
  • Select an option

  • Save sat0b/2e739419732599d6767f19711cadc66d to your computer and use it in GitHub Desktop.

Select an option

Save sat0b/2e739419732599d6767f19711cadc66d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <functional>
#include <gtest/gtest.h>
#include <glog/logging.h>
using namespace std;
namespace myhash {
enum Status {
Empty = 0,
Deleted,
Used,
};
template<typename T>
struct Table {
Status status;
string key;
T value;
};
template<typename T>
class HashTable {
public:
HashTable() {
for (int i = 0; i < MAX_SIZE; i++)
table[i].status = Empty;
}
void set(string key, T value) {
int hashed_key = myhash(key);
int count = 0;
while (table[hashed_key].status != Empty) {
hashed_key = (hashed_key + 1) % MAX_SIZE;
if (++count >= MAX_SIZE)
throw out_of_range("Hash table filled");
}
table[hashed_key].status = Used;
table[hashed_key].value = value;
table[hashed_key].key = key;
}
T get(string key) {
int hashed_key = myhash(key);
int count = 0;
while (table[hashed_key].status != Empty) {
if (table[hashed_key].status != Deleted && table[hashed_key].key == key)
return table[hashed_key].value;
hashed_key = (hashed_key + 1) % MAX_SIZE;
if (++count >= MAX_SIZE)
throw out_of_range("Hash table filled");
}
throw out_of_range("key : " + key + " not found");
}
void del(string key) {
int hashed_key = myhash(key);
int count = 0;
while (table[hashed_key].status != Empty) {
if (table[hashed_key].status != Deleted && table[hashed_key].key == key) {
table[hashed_key].status = Deleted;
return;
}
hashed_key = (hashed_key + 1) % MAX_SIZE;
if (++count >= MAX_SIZE)
throw out_of_range("Hash table filled");
}
};
private:
const static int MAX_SIZE = 1024;
Table<T> table[MAX_SIZE];
std::hash<std::string> hash_fn;
string key;
T value;
int myhash(string key) {
return hash_fn(key) % MAX_SIZE;
}
};
TEST(HashTable, get) {
HashTable<int> ht;
ht.set("foo", 1);
ht.set("bar", 2);
EXPECT_EQ(1, ht.get("foo"));
EXPECT_EQ(2, ht.get("bar"));
}
TEST(HashTable, del) {
HashTable<int> ht;
ht.set("foo", 1);
ht.del("foo");
EXPECT_THROW(ht.get("foo"), out_of_range);
}
} // namespace myhash
int main(int argc, char **argv) {
#ifdef RUN_TEST
LOG(INFO) << "start!";
google::SetLogDestination(google::GLOG_INFO, ".");
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
#endif
return 0;
}
@sat0b
Copy link
Author

sat0b commented Oct 22, 2017

clang++ hashtable.cpp -std=c++11 -Wall -g -lglog -lgtest -lgtest_main -D RUN_TEST && ./a.out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment