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?
c ++ vector stl stdvector
Jvpen
source share