This question made me uncertain about appending a vector to itself. So the question is: Following lines of code do what I expect, but is it standard conform?
vec.reserve(vec.size() * 2):
vec.insert(vec.end(), vec.begin(), vec.end());
Following (without reserve()
) still works, is it even standard conform?
vec.insert(vec.end(), vec.begin(), vec.end());
Or implementation depending?
According to the C++03 ISO spec (§23.1.1, Table 67) (and as @AndyProwl has mentioned, in §23.2.3, table 11 of the C++11 ISO spec), as part of sequence requirements, the operation a.insert(p, i, j)
in a sequence container has this precondition:
i
,j
are not iterators intoa
.
In other words, sequence containers are allowed to safely assume that if you do a range insertion operation, that range will not be defined from iterators over that original container.
As a result, if you try to insert a container's elements into itself, you are calling a standard library function and breaking a precondition. This results in undefined behavior, meaning that it might work on some platforms if the library implementers are nice people, but it could terribly and catastrophically fail with no justification.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With