Pergunta

std::list<my_type> my_list;
std::list<my_type>::iterator my_iter = my_list.begin();
std::list<my_type>::iterator my_prev = std::prev(my_iter);

What is the value of my_prev?
Is it my_list.rend(), even though it is technically a different type?
How to check for such condition besides my_iter == my_list.begin()?

Foi útil?

Solução

According to C++11 standard:

24.4.4 Iterator operations [iterator.operations]  
§ 7
template <class BidirectionalIterator>  
BidirectionalIterator prev(BidirectionalIterator x,  
typename std::iterator_traits<BidirectionalIterator>::difference_type n = 1);  
Effects: Equivalent to advance(x, -n); return x;  

In the same section, but §2 and §3

template <class InputIterator, class Distance>  
void advance(InputIterator& i, Distance n);  
Requires: n shall be negative only for bidirectional and random access iterators.
Effects: Increments (or decrements for negative n) iterator reference i by n.  

Then, for decrementing bidirectional iterators:

24.2.6 Bidirectional iterators
Expression  Return type Operational       Assertion/note
                          semantics     pre-/post-condition

                                        pre: there exists s such that
--r         X&                          r == ++s.
                                        post: r is dereferenceable.
                                        --(++r) == r.
                                        --r == --s implies r == s.
                                        &r == &--r.

So, it looks like (or at least I couldn't find more relevant part from the standard), that this behavior is not defined.

I'd suggest you to maintain this situation and be careful with my_iter's value, before passing it to std::prev.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top