【发布时间】:2013-03-25 10:29:33
【问题描述】:
我正在阅读“list::splice”的工作原理,但我不明白:
mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element)
mylist2.splice (mylist2.begin(),mylist1, it);
// mylist1: 1 10 20 30 3 4
// mylist2: 2
// "it" is now invalid.
it = mylist1.begin();
std::advance(it,3); // "it" points now to 30
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20
在第一个和第三个拼接中 it 迭代器仍然有效,但为什么它在第二个拼接中不存在?
根据文档:
迭代器有效性
迭代器、指针和引用没有变化 调用前与容器相关。 迭代器、指针和 引用转移元素的引用继续引用 那些相同的元素,但迭代器现在迭代到容器中 元素已被转移到。
因此它应该仍然有效
【问题讨论】:
-
那个资源是出了名的不准确。用一磅盐吃掉它所说的任何东西。
-
cppreference 也这么说:en.cppreference.com/w/cpp/container/list/splice
-
@JohnnyPauling:我在 cppreference 上没有看到这一点,他们明确表示 no 迭代器被
splice无效。 -
在哪里?我只看到它说“没有迭代器或引用失效”。
-
@DanielFrey 问题依然存在,迭代器在第二次拼接后无效,而 cppreference 声明它应该保持有效