Keeping std::list iterators valid through insertion

前端 未结 4 1542
南笙
南笙 2020-12-20 21:16

Note: This is not a question whether I should \"use list or deque\". It\'s a question about the validity of iterators in the face of insert().


4条回答
  •  执笔经年
    2020-12-20 21:48

    I was indeed being dense. The standard gives us all the tools we need. Specifically, the sequence container requirements 23.2.3/9 say:

    The iterator returned from a.insert(p, i, j) points to the copy of the first element inserted into a, or p if i == j.

    Next, the description of list::insert says (23.3.5.4/1):

    Does not affect the validity of iterators and references.

    So in fact if pos is my current iterator inside the list which is being consumed, I can say:

    auto it = buf.insert(buf.end(), newdata.begin(), newdata.end());
    
    if (pos == buf.end()) { pos = it; }
    

    The range of new elements in my list is [it, buf.end()), and the range of yet unprocessed elements is [pos, buf.end()). This works because if pos was equal to buf.end() before the insertion, then it still is after the insertion, since insertion does not invalidate any iterators, not even the end.

提交回复
热议问题