Quick way to get an iterator to the last element of a list

Started by
14 comments, last by Andrew Russell 18 years, 10 months ago
Quote:Original post by Red Ant
No, because by the time I'm going to delete a particular instance from the list it is perfectly possible that it will no longer be the last (or the first, for that matter) element in the list.


If it might not be that last element, then why are you trying to get the last element? (Just wondering)

Here's a possible solution:
Or not
Advertisement
Quote:Original post by Red Ant
Because once an iterator points to the end it's not really a valid iterator anymore (or is it?)

Actually, it is still a valid iterator, you just aren't allowed to dereference it (punishable by undefined behavior), but decrementing it should be perfectly fine if it's at least a bidirectional iterator (and the list is non-empty), which std::lists iterators are.
Quote:Original post by Programmer16
Quote:Original post by Red Ant
No, because by the time I'm going to delete a particular instance from the list it is perfectly possible that it will no longer be the last (or the first, for that matter) element in the list.


If it might not be that last element, then why are you trying to get the last element? (Just wondering)

Here's a possible solution:
Or not


Well, using my initial approach, it is the last element at the time I'm getting an iterator to it. But later, when I want to erase the element, it may no longer be the last element in the list (others may have been appended in the meantime).

How about

int myValue = 10;
std::list<int>::iterator it = myList.insert(myList.begin(), myValue);

hold on to iterator it for later?
How about using a map instead so you can keep a reference to any and all elements?
Gary.Goodbye, and thanks for all the fish.
Quote:Original post by garyfletcher
How about using a map instead so you can keep a reference to any and all elements?

Because you can keep a valid reference to any and all elements of a list...?

A map is a rather different data structure.



The following solution is quoted for being the correct solution:

Quote:Original post by DrEvil
How about

int myValue = 10;
std::list<int>::iterator it = myList.insert(myList.begin(), myValue);

hold on to iterator it for later?

That is precicely what you need to do. You can also be inserting at the .end() - or wherever you would like your item to go. Wonderful [smile].

This topic is closed to new replies.

Advertisement