This does not work. It gives an error regarding ISO C++ forbidding initialization.
class hash_map
{
private:
hash_entry **table;
const int TABLE_SIZE = 128;
public:
hash_map()
{
table = new hash_entry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
int get(int key)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == NULL)
return -1;
else
return table[hash]->getValue();
}
void put(int key, int value)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != NULL)
delete table[hash];
table[hash] = new hash_entry(key, value);
}
~hash_map()
{
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL) delete table[i];
delete[] table;
}
};
This is the cause of the compilation error. It is allowed in C++11 only, not in C++03 and C++98.
Either make it a
staticmember of the class, OR initialize it in the constructor. Make use of member-initialization-list for it.Apart from that dont forget to implement copy-semantics following Rule of Three, OR disable it altogether by declaring them (don’t define them) in the
privatesection. I think, disabling it would make more sense in this case.