Skip to content
Snippets Groups Projects
Commit b150843e authored by Peter Gerwinski's avatar Peter Gerwinski
Browse files

Hash-Tabelle: Lösung zu Aufgabenteil (a)

parent e0cf3799
No related branches found
No related tags found
No related merge requests found
#include <iostream>
#include <string>
using namespace std;
template <typename argtype>
class HashTable
{
private:
class HashEntry
{
private:
string key;
argtype value;
public:
HashEntry (string key, argtype value)
{
this->key = key;
this->value = value;
}
string getKey () { return key; }
argtype getValue () { return value; }
};
HashEntry **table;
int size;
// Create numerical representation of a string
int calcHash (string key)
{
int num = 0;
for (string::iterator it = key.begin(); it != key.end(); it++)
{
num += int (*it);
}
return num;
}
public:
// Initialize table
HashTable (int size)
{
this->size = size;
this->table = new HashEntry *[size];
for (int i = 0; i < size; i++)
{
table[i] = NULL;
}
}
// Get element by key
argtype get (string key)
{
int keyHash = calcHash(key);
int hash = (keyHash % size);
// prevent using same table slot multiple times
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % size;
if (table[hash] == NULL)
return NULL;
else
return table[hash]->getValue();
}
// Add element to table
void put (string key, argtype value)
{
int keyHash = calcHash (key);
int hash = (keyHash % size);
// prevent using same table slot multiple times
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % size;
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry (key, value);
}
// Destructor
~HashTable ()
{
for (int i = 0; i < size; i++)
{
if (table[i] != NULL)
delete table[i];
}
delete[] table;
}
};
int main ()
{
HashTable <string> str_table (4);
str_table.put("author", "Martin Sura");
str_table.put("date", "29.04.2018");
str_table.put("version", "1.0");
str_table.put("comment", "Hash table using own implementation.");
HashTable <int> int_table (4);
int_table.put("author", 1);
int_table.put("date", 2);
int_table.put("version", 3);
int_table.put("comment", 4);
cout << "Hash Table with string content: " << endl;
cout << "author: " << str_table.get("author") << endl;
cout << "date: " << str_table.get("date") << endl;
cout << "version: " << str_table.get("version") << endl;
cout << "comment: " << str_table.get("comment") << endl;
cout << "\nHash Table with int content: " << endl;
cout << "author: " << int_table.get("author") << endl;
cout << "date: " << int_table.get("date") << endl;
cout << "version: " << int_table.get("version") << endl;
cout << "comment: " << int_table.get("comment") << endl;
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment