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()
.
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 intoa
, orp
ifi == 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.