迭代过去双向链表的前面

时间:2014-02-21 14:56:59

标签: c++ list c++11 iterator c++-standard-library

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);

my_prev的价值是什么?
它是my_list.rend(),即使它在技术上是一种不同的类型吗? 除my_iter == my_list.begin()以外如何检查这种情况?

1 个答案:

答案 0 :(得分:0)

根据C ++ 11标准:

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;  

在同一部分,但§2和§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.  

然后,为了递减双向迭代器:

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.

所以,看起来(或者至少我找不到标准中更相关的部分),这种行为没有定义。

我建议你保持这种情况,并在将my_iter传递给std::prev之前小心{{1}}。