Search code examples
c++operator-overloadinghashtable

Operator [] overload for hash table


i want to overload the [] operator to use in a hash table i have to do for homework. I am using a vector of lists that contain pairs.std::vector <std::forward_list<std::pair<std::string, int>>> What i want from the operator to do is to return the other part of the given pair , for instance if there is a pair("test" , 21) , by writing vectorname["test"] i should get 21 , or if i were to write vectorname["test"]=22 it should modify the pair.Also , there should be no identical keys , or if they were to be ,only the first one would be taken into consideration. This is my first stack overflow question , sorry if i didn't explait things very well.


Solution

  • In order to do this sort of thing, you need to have your operator[] return a reference-like type that can be assigned to (in order to update the table) or just used (when reading the hash table). The critical thing you need to decide is what to do when the key is not present in the table.

    • add the key to the table immediately. This means that when you try to read a key that is not present, you'll add it to the table with a defaulted value (this is how STL maps work)
    • don't add the key until you actually assign to the element. This is more work, but allows you to have key values without a default constructor.

    In the former case, you just return an actual reference to the element value. In the latter case, you need to implement a custom element_ref class that can be assigned to (operator=) or can be implicitly converted to the element value type (operator int in your case).