Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I insert a vector to itself with std::vector::insert?

Is it allowed by the C++03 standard to append a std::vector to itself? I wonder if the source iterators can become invalid if v needs to reallocate memory. In my STL implementation, the old memory is kept until the new memory has been created. But can I rely on this? If not, is v.reserve(2 * v.size()) before the insert a good solution to avoid the reallocation altogether?

vector<int> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(3);
// v may need to reallocate because its capacity may be less than 6.
// Is this operation safe?
v.insert(v.end(), v.cbegin(), v.cend());

or

// Here v will _not_ need to reallocate because it has enough capacity.
// Is this operation safe?
v.reserve(2 * v.size());
v.insert(v.end(), v.cbegin(), v.cend());
like image 637
Fabian Avatar asked May 04 '26 18:05

Fabian


1 Answers

Regardless of whether perform reserve in advance or not, the behavior is undefined. For std::vector::insert:

inserts elements from range [first, last) before pos.

The behavior is undefined if first and last are iterators into *this.

like image 186
songyuanyao Avatar answered May 06 '26 08:05

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!