hashing example

This commit is contained in:
madmaurice 2016-02-08 14:18:22 +01:00
parent e7714fa372
commit 1b9e60564a
1 changed files with 71 additions and 0 deletions

71
hashing.cpp Normal file
View File

@ -0,0 +1,71 @@
#include <cstdio>
using namespace std;
template<
typename TElem,
std::size_t NSize>
class HashList {
private:
typedef struct {
std::size_t index;
TElem elem;
} entry;
entry* entries[NSize];
std::size_t create_hash(std::size_t const index, std::size_t const e) {
return (index + e) % NSize;
}
public:
HashList() {
for(std::size_t i = 0; i < NSize; i++) entries[i] = NULL;
}
bool insert(std::size_t index, TElem elem) {
std::size_t hash = 0;
std::size_t e = 0;
for(; e < NSize; e++) {
hash = this->create_hash(index, e);
if(entries[hash] == NULL) break;
}
printf("Inserting %d had %d collisions\n", index, e);
if(entries[hash] != NULL) return false;
entries[hash] = new entry{index,elem};
return true;
}
entry* find(std::size_t index) {
std::size_t hash = 0;
std::size_t e = 0;
for(; e < NSize; e++) {
hash = this->create_hash(index, e);
if(entries[hash] == NULL || entries[hash]->index == index) break;
}
printf("Finding %d had %d collisions\n", index, e);
if(entries[hash] != NULL && entries[hash]->index != index) return NULL;
return entries[hash];
}
};
int main( int argc, char *argv[] ) {
HashList<float, 13> l;
l.insert(1024, 2.5f);
l.insert(204, 1.5f);
l.insert(217, 1.0f);
printf("1024: %.1f\n", l.find(1024)->elem);
printf("204: %.1f\n", l.find(204)->elem);
printf("217: %.1f\n", l.find(217)->elem);
return 0;
}