getting reference to a STL map element

J

Jan

Hi there,
yes im a STL newbie, but thanks for replying.
I want to get a reference to an item included in a STL map. e.g.:

map<type1, type2> myMap;
.....
type2& aName = myMap[type1];
.....

what's wrong with this ;-) ? I don't want to have a copy of type2. only
a
reference to it (and if type1 is not in the map, it should be
automatically be
created)

thanks,
Jan
 
V

Victor Bazarov

Jan said:
yes im a STL newbie, but thanks for replying.
I want to get a reference to an item included in a STL map. e.g.:

map<type1, type2> myMap;
....
type2& aName = myMap[type1];
....

what's wrong with this ;-) ?

You cannot use 'type1' in the expression, that's what's wrong. Read
the FAQ, especially 5.8.
> I don't want to have a copy of type2. only
a
reference to it (and if type1 is not in the map, it should be
automatically be
created)

Try your best to write your program, then if you get errors, post back
with them (read the suggested FAQ).

V
 
M

Marcus Kwok

Jan said:
Hi there,
yes im a STL newbie, but thanks for replying.
I want to get a reference to an item included in a STL map. e.g.:

map<type1, type2> myMap;
....
type2& aName = myMap[type1];
....

what's wrong with this ;-) ?

You cannot index into a map with just a type. For example, the
following works for me:

#include <iostream>
#include <map>

typedef int type1;
typedef char type2;

int main()
{
std::map<type1, type2> myMap;
type1 key = 5;

// use explicit key
type2& aName = myMap[key];
aName = 'c';
std::cout << "myMap[key] = " << myMap[key] << '\n';

// use default value of type1 as the key (in this case, 0)
type2& anotherName = myMap[type1()];
anotherName = 'b';
std::cout << "myMap[type1()] = " << myMap[type1()] << '\n';

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top