Question: I'm trying to walk through this C++ code to comment each line and function as to what the lines and functions are supposed to do.

I'm trying to walk through this C++ code to comment each line and function as to what the lines and functions are supposed to do. As a whole, the program is a simple hash table program and works fine. I'm just hopeing someone can help me code the lines and understand what each piece is doing. Thank you. .

#include #include #include

using namespace std;

//Hash table class class HashTable { private: vector table; //vector array table int maxSize; //private member variable public: HashTable(); //default constructor unsigned long hash(string key); //member function (hash algorithm) bool insert(string key, int val); //member function int get(string key); //getter member function int &operator [](string key); //operator overload };

//----------------CLASS FUNCTIONS

//constructor function for the class HashTable::HashTable() { maxSize = 100; //initialize the private variable to table = vector(maxSize); //table will populate with the array of max sizing for(int i = 0; i < maxSize; ++i) //loop through the table { table[i] = -1; } }

//djb2 hash algorithm unsigned long HashTable::hash(string key) { unsigned long hash = 5381; //starting hash number for(int i = 0; i < key.size(); ++i) { hash = ((hash << 5) + hash) + ((int)key[i]); //binary shift and add calculation //https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm

} return hash; }

//function to insert the value into the table bool HashTable::insert(string key, int val) { unsigned long hashVal = hash(key); //connect the value to the hash key hashVal %= maxSize; if(table[hashVal] == -1) { table[hashVal] = val; return true; } else { return false; } }

//get int HashTable::get(string key) { unsigned long hashVal = hash(key); hashVal %= maxSize; return table[hashVal]; }

int &HashTable::operator[](string key){ unsigned long hashVal = hash(key); hashVal %= maxSize; return table[hashVal]; }

int main() { HashTable h; string s1 = "John"; string s2 = "Jake"; string s3 = "Jane"; h.insert(s1, 18); h.insert(s2, 21); h.insert(s3, 19); cout << "Jane: " << h.get(s3) << endl; string s4 = "Joanne"; h[s4] = 20; cout << "Joanne: " << h.get(s4) << endl; cout << "Joanne: " << h[s4] << endl; /* //auto never works on my Mac, so I code without it int count = 0; for (auto item : h) cout << count++ << " " << item << endl; */ }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!