splice() on std::list and iterator invalidation

前端 未结 3 1445
孤城傲影
孤城傲影 2020-12-11 02:21

The 3-argument form of list::splice() moves a single element from one list to the other. SGI\'s documentation explicitly states that all iterators, includi

相关标签:
3条回答
  • 2020-12-11 02:46

    I have an array of lists (equivalence classes of elements), and I'm using splice to move elements between the lists. I have an additional array of iterators which gives me direct access to any element in any of the lists and to move it to another list. None of the lists is searched and modified at the same time. I could reinitialize the element iterator after splice, but it's kinda ugly.. I guess I'll do that for the time being.

    0 讨论(0)
  • 2020-12-11 02:48

    The problem is that if the iterator still points to the element that was moved, then the "end" iterator previously associated with the "moved" iterator has changed. Unless you write some complex loop, this is actually a bad thing to do -- especially since it will be more difficult for other developers to understand.

    A better way in my opinion is to use the iterators pointing to the elements prior and after the moved iterator.

    0 讨论(0)
  • 2020-12-11 03:00

    Ok, this seems to be a defect in the standard, according to this and this link. It seems that "sticking the head in the sand" is a good strategy, since it will be fixed in new library versions.

    0 讨论(0)
提交回复
热议问题