为什么std :: vector迭代器在delete()调用之后无效? [英] Why std::vector iterator is invalidated after the erase() call?

查看:68
本文介绍了为什么std :: vector迭代器在delete()调用之后无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++参考明确指出,在迭代器上调用std::vector::erase(it)将使所有指向被擦除元素及其后的迭代器无效. http://en.cppreference.com/w/cpp/container/vector/erase

The C++ reference clearly state that calling std::vector::erase(it) on iterator will invalidate all iterators pointing to and after the erased element. http://en.cppreference.com/w/cpp/container/vector/erase

我确实理解为什么在erase调用之后,此类迭代器变得不可引用,但是我很好奇为什么他们必须变得无效,实现细节要求什么?

I do understand why such iterators became non-dereferenceable after the erase call, but i am curious why they need to became invalid, what implementation details require it?

例如,标准说std::vector必须使用连续存储的元素来实现,而elements can be accessed not only through iterators, but also using offsets on regular pointers to elements这样看来,将此类容器的迭代器可能实现为指针似乎是合乎逻辑的-但是指针如何变得无效?

For instance standard says that std::vector must be implemented with elements stored contiguously and that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements so it seems logical that iterators for such container will probably be implemented as pointers - but then how pointers could became invalidated?

推荐答案

iterator 概念概念所基于的原理之一如下:只要迭代器保持非别名即可,可取消引用且不可修改,则应引用同一实体.换句话说,多次取消引用相同的迭代器应产生相同的值.使用迭代器的算法可能依赖于此.

One of the principles on which the conceptual idea of iterator is built, is as follows: as long as iterator remains non-aliased, dereferenceable and non-modified, it should refer to the same entity. In other words, dereferencing the same iterator multiple times should yield the same value. Algorithms that use iterators may rely on that.

您提议的结果将导致迭代器神奇地"更改其引用的值,即使迭代器本身保持不变.在迭代器的概念范围内,这是不可接受的.

What you proposing would result in an iterator that would "magically" change the value it refers to even though the iterator itself remains unchanged. This is not acceptable within the conceptual idea of iterator.

第二个想法,我上面所说的显然有缺陷,因为我们总是可以对向量进行一些修改操作,以使元素四处移动(例如std::random_shuffle).这样的操作不会使任何迭代器无效,但是很容易更改迭代器引用的值.这与erase触发的元素移动有何不同?不是.

On the second thought, what I said above is obviously flawed in a sense that we can always apply some modifying operation to the vector that shifts elements around (e.g. std::random_shuffle). Such operation would not invalidate any iterators, but would easily change the values the iterators refer to. How is that different from element shifting triggered by erase? It isn't.

这篇关于为什么std :: vector迭代器在delete()调用之后无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆