I’m having difficulty assigning a value to a string. The string is contained in a struct. Here is the full code. It’s largely incomplete(I’m trying to get this to work before fixing my iterator)
It fails at operator[]
:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
template <class Key,class Value>
class hashMap
{
public:
explicit hashMap( int size = 101 ) : arraySize( size ){
array.reserve(arraySize+1);
}
hashMap(const hashMap & rhs){
arraySize = rhs.arraySize;
array.reserve(arraySize);
for(int i = 0; i < arraySize; i++)
{
array[i] = rhs.array[i];
}
}
~hashMap()
{
}
hashMap & operator=(const hashMap & rhs){
if (&rhs != this)
{
arraySize = rhs.arraySize;
array.clear();
array.reserve(arraySize);
for(int i = 0; i < arraySize; i++)
{
array[i] = rhs.array[i];
}
}
}
Value & operator[](const Key & key)
{
unsigned long long pos = hash(key, arraySize);
unsigned long long quad = 1;
while (array[pos].active != false && array[pos].first != key)
{
pos += quad;
pos %= arraySize;
quad *= 2;
}
array[pos].first = key; // FAILS HERE
array[pos].active = true;
return array[pos].second;
}
struct cell{
Key first;
Value second;
bool active;
cell(){
active = false;
}
};
class const_iterator
{
public:
cell operator*()
{
return array[pos];
}
private:
int pos;
};
private:
vector<cell> array;
int arraySize;
int hash(const std::string & key, int tableSize)
{
int hashVal = 0;
for(int i = 0; i < key.length(); i++)
{
hashVal = 37 * hashVal + key[i];
}
hashVal %= tableSize;
if(hashVal < 0)
{
hashVal += tableSize;
}
return hashVal;
}
int hash(int key, int tableSize)
{
return key%tableSize;
}
};
I would very much appreciate the help!
~A hopeless computer science student
In your constructors you use
but
std::vector::reserveonly reserves some memory for easy array expansion and does not create elements (nor resizes array). So, your cells don’t get constructed.Then, when you are trying to assign something to array, you are actually go out of array range.
You should use
std::vector::resizeinstead ofstd::vector::reserve(as a simplest solution)