向量中允许的活动迭代器数量

发布于 2024-09-13 06:29:17 字数 277 浏览 6 评论 0原文

例如以下内容有效吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

極樂鬼 2024-09-20 06:29:17

是的,这是有效的。

您可以在向量中添加尽可能多的迭代器,只要您的系统有足够的内存来容纳迭代器。

这种类型的容器的特殊名称是“任何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?

寄居人 2024-09-20 06:29:17

只要您不执行导致其他迭代器无效的操作,迭代器的数量就没有任何限制。某些操作(如插入或删除)可能会使所有其他迭代器无效。 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.

全部不再 2024-09-20 06:29:17

这绝对是允许的。您需要担心的是是否开始删除或插入元素。不同的容器通过修改函数来使迭代器失效有不同的行为,您必须查看文档。例如,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 a vector, for example, invalidates all iterators and element references after the element that was erased.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文