Home

Daniel T. wrote:

> In article <cLidnSe9sp-m9GnbnZ2dnUVZ_gudnZ2d@comcast.com>,
> "Howard" <me@here.com> wrote:
>
>> "Mark P" <usenet@fall2005REMOVE.fastmailCAPS.fm> wrote in message
>> news:c%YIi.54627$YL5.28332@newssvr29.news.prodigy.net...
>> > Ian Collins wrote:
>> >> Howard wrote:
>> >>> Is there an easy way to get an iterator (*not* a reverse-iterator) to
>> >>> the last element in a list? The last() function returns the element
>> >>> itself, not an iterator.
>> >>>
>> >> How about list.end()-1 or list.start()+(list.size()-1)
>> >>
>> >
>> > list iterators are bidirectional, not random access, so you can't do
>> > arithmetic like this. Not to mention that list.size() is O(n).
>> >
>> > But you can do:
>> >
>> > list<T>::iterator it = l.end();
>> > if( !l.empty())
>> > --it;
>> >
>> > Now "it" points to either the last element or, if the list is empty,
>> > end().
>>
>> Yeah, that's what I'm doing now, but I was hoping for a single expression
>> I
>> could use. This is working fine.
>
> assert( !l.empty() );
> list<T>::iterator it = --l.end();

I prefer your other idea:

list<T>::iterator it = l.rbegin().base();

This is more generic, e.g. you can use it in algorithms templated on
containers:

template < typename Container >
typename Container::iterator
last_iter ( Container & c ) {
return ( c.rbegin().base() );
}

will always work whereas

template < typename Container >
typename Container::iterator
last_iter ( Container & c ) {
return ( -- c.end() );
}

can fail for std::vector where the iterator type might be a naked pointer.



Best

Kai-Uwe Bux

previous
next

Re: The least used keywords in C++, which do you use?
Re: Faster std::map?
Re: list index()
Re: psycopg2 or pygresql?
Re: exception raised in destructor
mlmfrustrationsabolished.com
części mitsubishi
laptop
forum pokerowe
asg