使用输入迭代器第二次遍历容器
traversing a container a second time with an input iterator
there is no guarantee that traversing a container a second time with an input iterator will move through the values in the same order.Also after an input iterator has been incremented, there is no guarantee that its prior value can still be dereferenced.
或
An InputIterator is an Iterator that can read from the pointed-to element. InputIterators only guarantee validity for single pass algorithms: once an InputIterator i has been incremented, all copies of its previous value may be invalidated.
为什么其先前值的所有副本都可能无效?这些陈述的概念是什么?
也就是说你的迭代器只能读取它当前指向的元素,它不知道前一个或下一个元素。
考虑让两个迭代器指向一个 std::list<T>
Item1 ---> Item2 ---> Item3 ---> Item4
Iter0 ----↑ ↑
Iter1----------------ˈ
想象如下增加这些:
Iter0 = Iter1;
Iter1++;
递增后,您的迭代器集将如下所示:
Item1 ---> Item2 ---> Item3 ---> Item4
Iter0 ------------------↑ ↑
Iter1------------------------------ˈ
Iter1
的前一个值存储在 Iter0
中,因此它始终指向 Iter1
之前的元素。
现在假设我删除了 Item2
。
Item1 ---> Item3 ---> Item4
Iter0 -??? ↑
Iter1-------------------ˈ
Iter1
仍然有效并指向 Item3
。
Iter0
是 Iter1
的先前值不再有效并指向 "nothing"(意味着取消引用此迭代器现在将被视为未定义行为)。
there is no guarantee that traversing a container a second time with an input iterator will move through the values in the same order.Also after an input iterator has been incremented, there is no guarantee that its prior value can still be dereferenced.
或
An InputIterator is an Iterator that can read from the pointed-to element. InputIterators only guarantee validity for single pass algorithms: once an InputIterator i has been incremented, all copies of its previous value may be invalidated.
为什么其先前值的所有副本都可能无效?这些陈述的概念是什么?
也就是说你的迭代器只能读取它当前指向的元素,它不知道前一个或下一个元素。
考虑让两个迭代器指向一个 std::list<T>
Item1 ---> Item2 ---> Item3 ---> Item4
Iter0 ----↑ ↑
Iter1----------------ˈ
想象如下增加这些:
Iter0 = Iter1;
Iter1++;
递增后,您的迭代器集将如下所示:
Item1 ---> Item2 ---> Item3 ---> Item4
Iter0 ------------------↑ ↑
Iter1------------------------------ˈ
Iter1
的前一个值存储在 Iter0
中,因此它始终指向 Iter1
之前的元素。
现在假设我删除了 Item2
。
Item1 ---> Item3 ---> Item4
Iter0 -??? ↑
Iter1-------------------ˈ
Iter1
仍然有效并指向 Item3
。
Iter0
是 Iter1
的先前值不再有效并指向 "nothing"(意味着取消引用此迭代器现在将被视为未定义行为)。