90 lines
2.5 KiB
C++
90 lines
2.5 KiB
C++
#include "hashTableChaining.h"
|
|
#include <iostream>
|
|
|
|
HashTable::HashTable() {
|
|
this->size = 0;
|
|
this->entries = nullptr;
|
|
this->setHashFunction("firstTwoLetters");
|
|
}
|
|
|
|
HashTable::HashFunction::HashFunction(std::string name,
|
|
hashFunctionPtr algorithm, int size) {
|
|
this->name = name;
|
|
this->algorithm = algorithm;
|
|
this->size = size;
|
|
}
|
|
|
|
void HashTable::insert(Ware *entry) {
|
|
int hashValue = this->hashFunction(entry->getBezeichnung());
|
|
hashValue = hashValue % this->size;
|
|
HashNode node;
|
|
node.key = entry->getBezeichnung();
|
|
node.ware = entry;
|
|
this->entries[hashValue].push_back(node);
|
|
}
|
|
|
|
void HashTable::print() {
|
|
std::cout << "=====================================" << std::endl;
|
|
for (int i = 0; i < this->size; i++) {
|
|
std::cout << i << " :\t";
|
|
for (auto it = this->entries[i].begin(); it != this->entries[i].end();
|
|
it++) {
|
|
if (it != this->entries[i].begin()) {
|
|
std::cout << "\t|\t";
|
|
}
|
|
std::cout << it->key;
|
|
}
|
|
std::cout << std::endl;
|
|
}
|
|
std::cout << "=====================================" << std::endl;
|
|
}
|
|
|
|
void HashTable::setHashFunction(std::string algorithmName) {
|
|
for (int i = 0; i < 5; i++) {
|
|
if (this->availableAlgorithms[i].name == algorithmName) {
|
|
this->hashFunction = this->availableAlgorithms[i].algorithm;
|
|
this->size = this->availableAlgorithms[i].size;
|
|
if (this->entries != nullptr) {
|
|
delete[] this->entries;
|
|
}
|
|
this->entries = new std::list<HashNode>[this->size];
|
|
return;
|
|
}
|
|
}
|
|
|
|
std::cerr << "The Hash Function provided was not found!" << std::endl;
|
|
}
|
|
|
|
const Ware *HashTable::search(std::string key) {
|
|
int hashValue = this->hashFunction(
|
|
key); // key is "hashed" and stored in the variable int hashValue
|
|
hashValue = hashValue % this->size;
|
|
for (auto it = this->entries[hashValue].begin();
|
|
it != this->entries[hashValue].end(); it++) {
|
|
if (it->key == key) {
|
|
return it->ware;
|
|
}
|
|
}
|
|
std::cout << "Ware with bezeichnung " << key << " not found!" << std::endl;
|
|
return nullptr;
|
|
}
|
|
|
|
bool HashTable::deleteItem(std::string key) {
|
|
int hashValue = this->hashFunction(key);
|
|
hashValue = hashValue % this->size;
|
|
|
|
for (auto it = this->entries[hashValue].begin();
|
|
it != this->entries[hashValue].end(); it++) {
|
|
if (it->key == key) {
|
|
delete it->ware;
|
|
it = this->entries[hashValue].erase(it);
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
int firstTwoLetters(std::string bezeichnung) {
|
|
return (int)(bezeichnung[0] + bezeichnung[1]);
|
|
}
|