请问C++中设置的擦除函数吗?改变其他元素的地址?
我有以下代码:
set<Key> test;
test.insert(key1);
test.insert(key2);
iter1 = test.find(key1);
iter2 = test.find(key2);
test.erase(iter1);
我的问题是,如果删除了 key1,现在我可以在测试中使用 iter2 来引用 key2 吗?
谢谢
I have the following code:
set<Key> test;
test.insert(key1);
test.insert(key2);
iter1 = test.find(key1);
iter2 = test.find(key2);
test.erase(iter1);
My question is, if key1 is deleted, now can I use iter2 to refer to key2 in test?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,set 的
erase
仅使指向已擦除元素的迭代器无效(请注意,这不一定适用于所有容器)。Yes, set's
erase
invalidates only iterators that point to the element that was erased (note that this is not necessarily true for all containers).关联容器 set、multiset、map 和 multimap 只需要使迭代器和对已擦除元素的引用无效。
在双端队列中,所有迭代器和引用都无效,除非被擦除的成员位于双端队列的末尾(前面或后面)(23.2.1.3/4),
在列表中,只有迭代器和对被擦除元素的引用无效(23.2.2.3/3),而在向量上,擦除点之后的每个迭代器和引用都无效(23.2.4.3/3)
Asociative containers set, multiset, map and multimap are required to only invalidate iterators and references to the erased elements.
In a deque all the iterators and references are invalidated, unless the erased members are at an end (front or back) of the deque (23.2.1.3/4),
in a list only the iterators and references to the erased element is invalidated (23.2.2.3/3) and on a vector every iterator and reference after the point of erase is invalidated (23.2.4.3/3)
严格来说,您必须检查“插入”操作的返回值,并确保
key1
和key2
比较不相等;否则iter1 == iter2
并擦除iter1
会使iter2
无效。但总的来说,请参阅前面的答案,删除迭代器只会使该迭代器无效,而不会导致其他迭代器无效。例子:
Strictly speaking you have to check the return value of the "insert" operation and ensure that
key1
andkey2
don't compare equal; otherwiseiter1 == iter2
and erasingiter1
invalidatesiter2
. But in general see the previous answer, erasing an iterator invalidates only that iterator and no others.Example: