By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,389 Members | 1,881 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,389 IT Pros & Developers. It's quick & easy.

getting reference to a STL map element

P: n/a
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

Dec 12 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jan wrote:
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
Dec 12 '05 #2

P: n/a
Jan <Ja*********@t-online.de> wrote:
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;
}
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)


--
Marcus Kwok
Dec 12 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.