Insertion into a vector with reference to the data of the same vector

I am in a situation where I would like to duplicate some elements in the 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 less than the final capacity, std :: vector should redistribute its internal data, making my link to the inserted data invalid.

The STL implementation that I am currently using (MSVC2013) contains protection against such inserts, as it will make a copy of my element if it needs to be redistributed. However, I'm not sure if I can rely on this behavior or do I need to make a copy first myself? (I would rather not look at such errors when upgrading to a new STL implementation)

In short: am I allowed to call insert () on a vector with a reference to an element in the same vector?

+7
c ++ vector stl stdvector
source share
1 answer

You're good.

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

but calling a.insert(p,n,t) , where n is the counter and t is the value that does not have such a requirement.

This was clearly raised as a problem in C ++ for 11 days, and it was closed because NAD with the justification " vector::insert(iter, value) is required to work, because the standard does not give permission for it to not work . "

+4
source share

All Articles