tags:

views:

118

answers:

2

Where does the C++ standard declare that the pair of iterators passed to std::vector::insert must not overlap the original sequence?

Edit: To elaborate, I'm pretty sure that the standard does not require the standard library to handle situations like this:

std::vector<int> v(10);
std::vector<int>::iterator first = v.begin() + 5;
std::vector<int>::iterator last = v.begin() + 8;
v.insert(v.begin() + 2, first, last);

However, I was unable to find anything in the standard, that would prohibit the ranges [first, last) and [v.begin(), v.end()) to overlap.

+3  A: 

Consider the behavior if it was allowed. Every insert into the vector would both increase the distance between the start and end iterator by one and move the start iterator up one. Therefore the start iterator would never reach the end iterator and the algorithm would execute until an out of memory exception occurred.

JaredPar
Are you saying that the standard does not explicitly state this requirement?
avakar
I checked it quickly and yes, it doesn't say it explicitly.
AraK
AraK, with all due respect, how could you possibly check something like that quickly?
avakar
@avakar I just checked **23.2.4.3 vector modifiers** and there isn't anything about your question. Sorry if I misunderstood the question :)
AraK
I mean, I didn't find the word "overlap" in any of the relevant places, but it can be formulated differently.
avakar
AraK, I believe you understood it right, it's just not enough to look in 23.2.4.3 (for the record, I checked too before asking). I do, however, appreciate your comment, sorry if I were jumpy. :-)
avakar
If it were allowed, then surely the standard would specify it in a way that didn't lead to an infinitely-sized vector. Like, say, require that it insert the values of that range of iterators as they were at the time of the call, irrespective of any changes made to the range during the call.
Rob Kennedy
+5  A: 

23.1.1/4 Sequence requirements has:

expression: a.insert(p,i,j)

return type: void

precondition: i,j are not iterators into a. inserts copies of elements in[i,j) before p.

So i and j cannot be iterators into your vector.

It makes sense, as during the insert operation, the vector may need to resize itself, and so the existing elements may first be copied to a new memory location (there by invalidating the current iterators).

Richard Corden
Thank you very much, this is exactly what I was looking for. :-)
avakar
Pretty sure you mean `i` and `j`, not `p`; `p` *must* be an iterator into the vector.
Rob Kennedy
Thanks for catching that Rob.
Richard Corden