向量中允许的活动迭代器数量
例如以下内容有效吗?
std::vector<int> vec(5, 0);
std::vector<int>::const_iterator it1(vec.begin());
std::vector<int>::const_iterator it2(vec.begin());
//Use it1 and it2 like they don't know about each other.
允许多个活动迭代器的容器是否有特殊名称?
For example is the following valid?
std::vector<int> vec(5, 0);
std::vector<int>::const_iterator it1(vec.begin());
std::vector<int>::const_iterator it2(vec.begin());
//Use it1 and it2 like they don't know about each other.
Is there a special name for a container that permits multiple active iterators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是有效的。
您可以在向量中添加尽可能多的迭代器,只要您的系统有足够的内存来容纳迭代器。
这种类型的容器的特殊名称是“任何STL容器”。所有容器都允许这样做。
也许解释一下为什么你认为这不应该被允许?
Yes, it's valid.
You can have as many iterators into a vector as your system has memory to hold iterators.
The special name for this type of container is "any STL container". All containers allow this.
Maybe explain why you think this shouldn't be allowed?
只要您不执行导致其他迭代器无效的操作,迭代器的数量就没有任何限制。某些操作(如插入或删除)可能会使所有其他迭代器无效。 STL 容器迭代器的工作方式是,它们(通常)无法处理通过其他迭代器完成的插入和删除操作。
请注意,使用容器函数插入/删除元素也会使迭代器无效。
根本问题是 STL 容器不知道有关活动迭代器的任何信息,因此它们无法告诉迭代器某些内容已发生更改。
As long as you don't do operations that render the other iterators invalid, there isn't any limit on the # of iterators. Some operations (like insert or remove) may render all of the other iterators invalid. The way STL container iterators work, there's no way for them to (generally) deal with insert and remove done through other iterators.
Note that using container functions to insert/remove elements will ALSO render the iterators invalid.
The underlying issue is that STL containers don't know anything about the active iterators, so they can't tell the iterators that something has changed.
这绝对是允许的。您需要担心的是是否开始删除或插入元素。不同的容器通过修改函数来使迭代器失效有不同的行为,您必须查看文档。例如,
vector
上的erase
会使擦除元素之后的所有迭代器和元素引用无效。That's definitely permissible. The thing you have to worry about is if you start erasing or inserting elements. Different containers have different behavior for invalidation of iterators by modifying functions, you'll have to look at the documentation.
erase
on avector
, for example, invalidates all iterators and element references after the element that was erased.