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()
之外,如何检查这种情况?
根据 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
之前保持这种情况并小心处理它。
我是一名优秀的程序员,十分优秀!