Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting in vector with reference to data of the same vector

I'm currently in a situation where I would like to duplicate some elements in a vector. In short, my code is similar to the following:

std::vector<MyStruct> v;
// ...
auto toDuplicate = std::find(v.begin(), v.end(), [](const MyStruct &s) { return true; /*In reality, a bit more complex*/ });
v.insert(toDuplicate, nrOfDuplicates-1, *toDuplicate);
// Signature: insert(iterator, size_t, const value_type &)

So, in this case, if the capacity is smaller than the final capacity, the std::vector has to realloc of its internal data making my reference the inserted data invalid.

The implementation of the STL I'm currently using (MSVC2013) contains protection against this kind of inserts as it will do a copy of my element if it needs to realloc. However, I'm not sure if I'm able to rely on this behavior or does it require me to first make a copy myself? (I'd rather prevent myself from looking at this kind of bugs when upgrading to a new STL implementation)

So in short: Am I allowed to call insert() on a vector with a reference to an element in that same vector?

like image 227
JVApen Avatar asked Apr 04 '16 12:04

JVApen


1 Answers

You're good.

if you look at table 99 (sequence container requirements), you'll see, for example, that a.insert(p,i,j) (where i and j are iterators) has the precondition: "i and j are not iterators into a".

but the call a.insert(p,n,t) where n is a count and t is a value has no such requirement.

This was explicitly raised as an issue back in the C++11 days, and it was closed as NAD with the rationale "vector::insert(iter, value) is required to work because the standard doesn't give permission for it not to work."

like image 156
Marshall Clow Avatar answered Oct 02 '22 15:10

Marshall Clow