Understanding list::splice

The definition for iterator validity after list::splice operation:

Iterator validity
No changes on the iterators, pointers and references related to the container before the call.
The iterators, pointers and references that referred to transferred elements keep referring to those same elements, but iterators now iterate into the container the elements have been transferred to.

Example Code:

...
1
2
3
4
5
6
7
8
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. 

...

I see a contradiction here.
From my understanding the meaning of:

"The iterators, pointers and references that referred to transferred elements keep referring to those same elements, but iterators now iterate into the container the elements have been transferred to."

Would lead to "it" still pointing to the value 2 in the container mylist2 in the above example.

Any explanations?
Last edited on
Iterators to moved elements remain valid. Seems pretty clear to me. You don't seem to have any actual question. You've just written some things and then said "Any explanations?"

Explanations for what? What does the code do that you think it shouldn't do, or what does it do that you don't understand?
"it" is now invalid.

This part of the example is incorrect. "it" refers to the element with value 2 in mylist2.
Last edited on
As Peter87 explained there is a contradiction in the definition and the comment in the example code: ' "it" is now invalid '. I would also assume it should refer to value 2 in mylist2 after the splice operation is performed. Does anyone else agree on this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <list>

int main() {
    using std::cout;
    std::list<int> a {0, 1, 2, 3, 4, 5}, b {10, 11, 12};

    auto it = b.begin();
    a.splice(a.begin(), b, it);
    cout << "it: " << *it   << '\n';  // 10; it is still valid
    cout << "it: " << *++it << '\n';  // 0; but it is part of list a now
   
    cout << "a: "; for (auto n: a) cout << n << ' '; cout << '\n';  // 10 0 1 2 3 4 5
    cout << "b: "; for (auto n: b) cout << n << ' '; cout << '\n';  // 11 12
}

Last edited on
Topic archived. No new replies allowed.