So I'm making a map class that uses a binary search tree. I can't figure out how I can make the [] operator return the address of the item. Here's what I have so far. Any help is appreciated.
1 2 3 4 5 6 7 8 9
VALUE_TYPE& Map::operator[](KEY_TYPE k ){
Map::Iterator it = find( k );
if( it == end() ){
insert( k, 0 );
it = find( k );
}
VALUE_TYPE val = *it->data;
return &val;
}
Why do you want the operator[] to return the address of the item? I assume your map is a class that maps KEY_TYPE to VALUE_TYPE, presumably as a class template? if that's true, the user would expect my_map[my_key] to return an object or reference of type VALUE_TYPE.
I think you're getting references confused with pointers. They can have similar use, at times. But I think you want to use references here, that's how the standard library does it.
See: http://www.cplusplus.com/reference/map/map/operator[]/
Before we continue the discussion, can you tell me why you don't want to do this?
1 2 3 4 5 6 7 8
VALUE_TYPE& Map::operator[](KEY_TYPE k ){
Map::Iterator it = find( k );
if( it == end() ){
insert( k, 0 );
it = find( k );
}
return it->data; // returning reference to the data you just found.
}
PS: IN your code, can you tell me what the lifetime of the variable "VALUE_TYPE val" on line 7 is?
i.e. when does it stop existing? This is an important concept to understand.