I'm trying to understand how std::list
iterators are affected after splice operations in C++11. Here is a small example that does not behave as I expect:
std::list<int> A({1, 2, 3});
std::list<int> B;
auto p = A.begin(), q = A.end();
auto p_copy = p, q_copy = q;
// True:
std::cout << "p == A.begin()? " << (p == A.begin()) << std::endl;
// True:
std::cout << "p_copy == A.begin()? " << (p_copy == A.begin()) << std::endl;
B.splice(B.end(), A, p, q);
// True:
std::cout << "p == B.begin()? " << (p == B.begin()) << std::endl;
// False, but I don't understand why:
std::cout << "p_copy == A.begin()? " << (p_copy == A.begin()) << std::endl;
// True, but I don't understand why either:
std::cout << "p_copy == B.begin()? " << (p_copy == B.begin()) << std::endl;
In this example, I don't understand why the p_copy
iterator no longer points to A.begin()
after the splice.
list
iterators point to elements. By splicing a range of elements, you've changed which container those iterators point into. The element is no longer an element of A
; it is an element of B
. Iterators are preserved across splice
ing, so p
and p_copy
will still point to those elements.
They're just iterators into different containers now.
Fundamentally because this is the defined behavior of list::splice
:
No iterators or references become invalidated, the iterators to moved elements remain valid, but now refer into
*this
, not into other.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.