I have a problem in my code which i can’t understand. I want to make a list of lists and use it like a two-dimensional associative array.
Something like this:
token["window"]["title"] = "Amazing!";
cout << token["window"]["title"]; //Amazing!
The second line works good. Data is readed from file. Problem is with the first instruction.
This is how i overload the second square brakcets:
TokenPair Token::operator[](string keyName){
for( list<TokenPair>::iterator pair=keys.begin(); pair != keys.end();++pair){
if(pair->key == keyName){
return *pair;
}
}
}
As you see I return object of class TokenPair. To properly get the value from object (field TokenPair::value) i overload streaming and casting on string().
TokenPair::operator string() const{
return value;
}
ostream & operator<< (ostream &stream, const TokenPair &pair){
return stream << pair.value;
}
And as i say before getting value works great. Problem is with overloading operator of attribution:
TokenPair TokenPair::operator=( const string newValue ){
value = newValue;
return *this;
}
This method assing the value but it not remember that! For example:
token["window"]["title"] = "Ok";
will cause that inside method TokenPair::operator= variable newValue==”Ok” and after the first line even value is set to “Ok”; But when i later do:
cout << token["window"]["title"] ;
the field in TokenPair is still not changed. I want to ask: Why? Maybe iterators return a copy of that object? I don’t know. Please help.
Here is an example of how to use a map-of-maps: