Re: Pointer to STL element address?
On May 25, 6:20 pm, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
Michael <comtech....@gmail.com> writes:
On May 25, 8:49 am, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
If the List was already inserted into the Map:
---------------
my_list.push_back(my_element);
std::list<YourElementType>::iterator pointer=my_list.end()-1;
my_map[key]=my_list;
---------------
Will this pointer be pointing to the correct location, i.e.
the address of my_element, even after being nested within
the Map?
No. On the other hand, if you do:
my_map[ key ].push_back( my_element ) ;
std::list<...>::iterator pointer = my_map[ key ].end() - 1 ;
you're safe. (Note that std::list<>::iterator is not a random
access iterator, so you can't add and subtract on it.) Use a
reference to the list if you're worried about performance:
my_list<...>& list = my_map[ key ] ;
list.push_back( my_element ) ;
std::list<...>::iterator pointer = list.end() ;
-- pointer ;
But in practice, the time necessary to insert an element in the
list will be large enough that the extra look-up won't matter.
Well, not really. In general iterators are rather volatile: a
lot of operations render them invalid.
That's not really true for node based containers, like list and
map. But you're right to warn about it---I can easily imagine
changing std::list to std::vector at some later time, for
performance reasons, and watching things break.
The problem is that a lot of operations with the STL actually
do COPY the objects, so called "value" semantic.
If you want to keep a pointer to the last 'object' you put in
a list, (be it a true C++ pointer, or a smart pointer of some
kind), I would advise to only put pointers (or smart pointers)
in your lists.
Generally, if it makes any sense to have a pointer to the
object, the object has identity, and can't be copied anyway. So
you have to use a container of pointers. Still, there are
exceptions, and I've used pointers to objects in an std::map on
a few rare occasions.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34