how to take a reference of inserted items?

L

lallous

Hello

Given this:

map<int, mystruct> m;
m[4] = item;
item.id++;
m[2] = item;

How can I get a direct refrence to the location of the just inserted item?
(which is now managed by the map)

I would do a find() then get a reference to its "second".

Same question <list> <vector> how can I get reference directly after
insertion? is the back() / front() the only way for this case?
 
V

Victor Bazarov

lallous said:
Given this:

map<int, mystruct> m;
m[4] = item;
item.id++;
m[2] = item;

How can I get a direct refrence to the location of the just inserted item?
(which is now managed by the map)

I would do a find() then get a reference to its "second".

That's not a bad idea.
Same question <list> <vector> how can I get reference directly after
insertion? is the back() / front() the only way for this case?

No. What if you inserted in the middle?

Dereferencing a non-const iterator gives you a reference. So, if you
use 'find' and then do

list<T>::iterator myObjIter = mylist.find(someT);
if (myObjIter != mylist.end()) {
T & myObjectRef = *myObjIter;
... // do something with 'myObjectRef'
}

However, keep in mind that references do become invalid, more often in
a 'vector' than in a 'list', but still.

Victor
 
M

Martin Eisenberg

lallous said:
Hello

Given this:

map<int, mystruct> m;
m[4] = item;
item.id++;
m[2] = item;

How can I get a direct refrence to the location of the just
inserted item? (which is now managed by the map)

I would do a find() then get a reference to its "second".

Same question <list> <vector> how can I get reference directly
after insertion? is the back() / front() the only way for this
case?

All of them have an insert() method that returns an iterator, so:

vector<int> v(3, 0);
list<int> l;
map<char, int> m;
int& rv = *v.insert(v.begin() + 1, 35);
int& rl = *l.insert(l.end(), 17);
int& rm = m.insert(make_pair('k', 80)).first->second;


Martin
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top