I am trying to overload the subscript operator [] in my class which uses a linked list to create a map. This and several variations, like adding const, is what I have tried.
header
int& operator[](std::string key); and then defining the overload in a seperate file
int& mapLL::operator[](std::string key){ int val = this->get(key); return val; } this is the error I don't know how to fix
main.cpp: In function ‘int main()’: main.cpp:38:24: error: invalid types ‘mapLL*[const char [4]]’ for array subscript int a = list3["ghi"]; ^ mapLL.cpp: In member function ‘int& mapLL::operator[](std::string)’: mapLL.cpp:110:9: warning: reference to local variable ‘val’ returned [-Wreturn-local-addr] int val = this->get(key); ^ Then in the main file I am trying this
mapLL *list3 = new mapLL(); list3->set("abc",1); list3->set("def",2); list3->set("ghi",3); list3->set("jkl",1); list3->toString(); cout << list3->get("ghi") << endl; int a = list3["ghi"]; cout << a << endl; delete list3; get function
int mapLL::get(std::string key){ bool found = false; node *me = (node *) first; if(is_empty()){ return -2; } while(!found){ if (me->getKey() == key){ return me->getValue(); }else{ if (me->getNext() == 0){ return -1; }else{ me = (node *) me->getNext(); } } } }
list3is a pointer, so you would have to do(*list3)["ghi"]list3as a local or global variable withoutnew.list3["ghi"]workslist3as a pointer. It doesn't need to be one.