I'm trying to implement Hash Table in c++ using STL list of pairs. Initial maxSize I set to 1, and I'd like to increase hash table's size twice as soon as its currentSize is greater than 75% of maximum capacity. I am getting error "Cannot dereference end list operator". Here is my implementation:
template<class V>
class HashTable {
public:
int currentSize;
int maxSize;
std::list<std::pair<std::string, V> > *arr;
HashTable() {
this->currentSize = 0;
this->maxSize = 1;
this->arr = new std::list<std::pair<std::string, V> >[maxSize];
arr->assign(maxSize, std::pair<std::string, V>());
}
~HashTable() {
delete[] arr;
}
void add(std::string key, V value) {
if (currentSize >= 0.75 * maxSize) {
rehash();
}
currentSize++;
int idx = hashFunction(key);
std::list<std::pair<std::string, int> >::iterator it = arr->begin();
std::advance(it, idx);
it = arr->erase(it);
arr->insert(it, std::pair<std::string, V> (key, value));
}
int hashFunction(std::string key) {
int total = 0;
for (int i = 0; i < key.length(); i++) {
total += int(key[i]) * pow(31, key.length() - i - 1);
}
return total % maxSize;
}
void rehash() {
maxSize *= 2;
std::list<std::pair<std::string, V> > *newArr = new std::list<std::pair<std::string, V> >[maxSize];
newArr->assign(maxSize, std::pair<std::string, V>());
for (auto it = arr->begin(); it != arr->end(); it++) {
int idx = hashFunction(it->first);
it = arr->begin();
std::advance(it, idx);
it = arr->erase(it);
newArr->insert(it, std::pair<std::string, V>(it->first, it->second));
}
delete[] arr;
arr = newArr;
}
Interesting fact to point is that when I hard-code the maxSize for example by setting it to 20 and then adding 2 elements, it works and outputs e.g. "1: abc -> 123, 5: bca -> 42".