Creating a Vector Duplicate
When appending a vector to itself, it's desirable to avoid using loops for performance reasons. The std::vector::insert function, while an option, doesn't allow using an iterator to *this.
Approaching the Problem with std::copy
Using std::copy to solve this issue may seem like a solution, but this approach can lead to segmentation faults.
The Optimal Solution
The optimal solution involves using both resize (or reserve) and copy_n. Here's how it works:
auto old_count = xx.size(); xx.resize(2 * old_count); std::copy_n(xx.begin(), old_count, xx.begin() + old_count);
This code first stores the original vector size in old_count. Then it resizes xx to double its capacity. Finally, std::copy_n copies the elements from the beginning of xx to the end of xx, effectively duplicating the vector.
Alternatively, you can use reserve instead of resize:
auto old_count = xx.size(); xx.reserve(2 * old_count); std::copy_n(xx.begin(), old_count, std::back_inserter(xx));
When using reserve, copy_n is essential since the end() iterator points beyond the end, making it invalid for insertions.
This approach satisfies the conditions outlined in 23.3.6.5 [vector.modifiers], ensuring that iterators and references before the insertion point remain valid, and no reallocation occurs if possible.
The above is the detailed content of How to Efficiently Duplicate a Vector in C Without Loops?. For more information, please follow other related articles on the PHP Chinese website!