Michael said:
On May 25, 8:49 am, (e-mail address removed) (Pascal J. Bourguignon)
wrote:
If the List was already inserted into 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.