Search code examples
c++operator-overloadingbrackets

operator[]= overload?


Okay, I'm trying to make a quick little class to work as a sort of hash table. If I can get it to work then I should be able to do this:

  StringHash* hash = new StringHash;
  hash["test"] = "This is a test";
  printf(hash["test"]);

And it should print out "This is a test".

It looks like I have 2 problems at this point. Firstly I did this:

const char* operator[](const char* key) {
  for(int i = 0; i < hashSize; ++i) {
    if(strcmp(hkeys[i], key) == 0) {return values[i];}
  }
  return NULL;
}

But when I try to look up a value the compiler complains that

error: invalid types `StringHash*[const char[5]]' for array subscript

Secondly operator[]= does not appear to be the correct syntax here. The only other thing I could find was &operator[] but I don't think that will work since I have to code the lookup procedure??? (Isn't that syntax just used to return an array item reference?)

Is what I'm trying to do here even possible? Any advice appreciated. :)


Seems to be some confusion about what I'm trying to do. I'll post my code:

http://pastebin.com/5Na1Xvaz


Finished product after all the help:

http://pastebin.com/gx4gnYy8


Solution

  • I would firstly question why you are writing your own HashMap when there are some versions available albeit not a standard one. (that was written in 2010, but there is now std::unordered_map)

    Does your hash-map store const char* pointers or std::strings? (It might store const char * pointers if it is simply a lookup table to data stored elsewhere that is not going to change its lifetime).

    What is operator[] supposed to do when the item is not found?

    Now let me assume that the answers are:

    • Yes we are storing const char * pointers, and we store a NULL in an empty cell
    • When we perform hash[key]=value we want to associate key with value
    • If we just do hash[key] but don't write, it does not insert

    This can be done with a magic object: when you assign a const char * to this object it inserts or overwrites to the hash. You can also have an implicit conversion from the object to const char * for reading.

    This is quite complex though and it is preferable to stick to the regular interface of map: operator[] always inserts and you use a different method just to lookup.