in the attempt to learn how hash tables really work, i decided to try implementing just a simple one (again working from the guidelines in Cormen, et al., Intro to Algorithms), where i'm storing key-value pairs where both key and value are strings and where duplicate keys are allowed.
Here's what I've got as header file to start with but wanted to hear whether this is right in terms of the basic structure of what a hash table actually is (no hash function implemented yet since this is just describing the structure):
i guess my own initial question would be on the search() function, which seems very basic at this point. Extrernally, the integer returned is useful only as flag for whether the key exists or not. even if you allow duplicates, i would think you'd eventually in practice at least want something that would give you a list (as return value in C++, std::vector<std::string> might be better than std::list<std::string> ?) of all values associated with the given key.Code:#ifndef HASH_TABLE_H #define HASH_TABLE_H #include <list> #include <utility> // for pair to get key-value pairs #include <string> typedef std::pair<std::string, std::string> KeyValue; // key-value pair where key and value are both strings typedef std::list<KeyValue> KeyValueList; const double SIZE_FACTOR = 1.33; class HashTable { private: KeyValueList * h_tbl; unsigned tbl_size; // size of the hash_table unsigned prime_generator(unsigned min); // will generate the next prime larger than min public: HashTable(const size_t size); ~HashTable() {delete [] h_tbl; } // constructor will clearly use new [] // basic hash_table operations, should all have average runtime of O(1): void insert(const KeyValue &item); /** @param key The key which is to be located @return If the key is found at some index, returns an index where it is found Note that if there are multiple instances of key, it will be unpredictable which one is returned If the key is not found anywhere, then -1 is returned */ int search(const std::string &key) const; /** @param key The key to find and delete. All instances of key should be deleted. @return Returns true iff the key was found and something was deleted. Returns false if key not found (in which case no action is taken). */ bool remove(const std::string &key); }; #endif



LinkBack URL
About LinkBacks



