Getting the Last Element in a List Container

How would go about doing this? I've tried:

std::list<int>::iterator iter = List.end ( )--;

But that doesn't exactly work, and ends up with an out-of-bounds assertion error. I know I could use a reverse iterator, but I need the iterator so that I can remove something from the list later on, and the erase() method doesn't work with reverse iterators.
Last edited on
Last edited on
The first returns the value, and the second one removes the last value in the list and returns it. Not what I'm looking to do.
If permissible, I would consider a container with random access for your application. Perhaps a deque or vector would better suit your requirements.
That works. I was just hoping that there was some way for me to do it without having to replace every reference to the list class. For some reason I got into the habit of using lists for everything and forgot about the other containers.
typedefs can be used to help out with that and also on Linux/UNIX systems refactoring can often be eased with grep/find/sed. For example:

> find -name '*.[hc]pp' -exec grep -Hn --color 'std::list' {} \;

Find all occurrences of the target string and verify that this expression does not pick up anything that you do not want to replace. If everything looks good, then perform the replace:

> find -name '*.[hc]pp' -exec sed -i 's/std::list/std::deque/g' {} \;

Just curious as to why you need to get an iterator to the last element in the list?
All of the STL algorithms and all of the STL itself in general works by specifying
the open-ended range [ first, last ), where last is "one past" the last element
in the range.
typedefs can be used to help out with that and also on Linux/UNIX systems refactoring can often be eased with grep/find/sed. For example:

> find -name '*.[hc]pp' -exec grep -Hn --color 'std::list' {} \;

Find all occurrences of the target string and verify that this expression does not pick up anything that you do not want to replace. If everything looks good, then perform the replace:

> find -name '*.[hc]pp' -exec sed -i 's/std::list/std::deque/g' {} \;
Er... how is that supposed to help me?

I need the last element in an iterator so I can get the position of a value that was just pushed onto the container.
std::list<int>::iterator iter = List.end ( )--;

rawr... postfix will return the value first and then decrement. Use this:

std::list<int>::iterator iter = --List.end ( );

Be sure to check for empty lists first.


By the way. I am as curious as jsmith about why you need the iterator to the end...

Ciao, Imi.
Topic archived. No new replies allowed.