Joe Davis Joe Davis - 10 months ago 77
C++ Question

Return the size of the hash table?

Excuse me in advance if I'm not explaining this clear..
Okay so I have declared a hash table using a vector like so:

> class HashTable{

vector<string> arrayofbuckets[100];

void insertelement(string input);
void deleteelement(string remove);
bool lookupelement(string search);
int tablesize();

> }; // end of class

I have also creating a menu using a switch statement to insert elements into the hash table:

> case 'I':
cout << " Which element would you like to insert?: ";
cin >> Element;



It then gets passed on to this function:

void HashTable::insertelement(string input){

int hashValue = 0;

for(int i = 0; i<input.length(); i++){

hashValue = hashValue + int(input[i]);


hashValue = hashValue % 100;

cout << " The element " << input << " has been put into value " << hashValue << ends;

Does anyone have any idea how to write a function to obtain and display the size of the table?

Answer Source

The best way is to keep track of the size inside functions that should initialise or modify it:

HashTable::HashTable() : size_(0) { }

void HashTable::insertelement(string input){ all the existing stuff...

// similarly --size_ inside deleteelement...

int HashTable::tablesize() const { return size_; }

Make sure you add an int size_; data member.

Do note that bool lookupelement(string search) const; and int tablesize() const; should be const - I've inserted the keyword here so you know where to put it, and used it above when defining tablesize().

If you were really determined to avoid an extra member variable, you could also do this...

int HashTable::tablesize() const {
    int size = 0;
    for (std::vector<std::string>& vs : arrayOfBuckets)
        size += vs.size();
    return size;

...but most users will expect a constant-time and fast size() function: they may call it every time through their loops, so keep it cheap.