Home >Backend Development >C++ >How to Efficiently Duplicate and Append a Vector to Itself?
Have you encountered the need to duplicate and append the contents of a vector to itself? If so, you may be seeking an elegant solution without resorting to explicit loops.
While std::vector::insert might seem like a suitable candidate, the iterative version exhibits undefined behavior if used with *this as an iterator. Additionally, std::copy alone can lead to segmentation faults.
Fear not! There is a simple and efficient approach that involves two steps:
Here's an example using resize:
auto old_count = xx.size(); xx.resize(2 * old_count); std::copy_n(xx.begin(), old_count, xx.begin() + old_count);
Alternatively, you can utilize reserve along with std::back_inserter:
auto old_count = xx.size(); xx.reserve(2 * old_count); std::copy_n(xx.begin(), old_count, std::back_inserter(xx));
Note that when using reserve, std::copy_n is essential since end() points to one past the end of the vector, making it invalid as an insertion point.
The above solutions ensure that the resulting vector contains the original elements duplicated and appended to themselves, preserving the integrity of the existing elements and minimizing reallocation operations.
The above is the detailed content of How to Efficiently Duplicate and Append a Vector to Itself?. For more information, please follow other related articles on the PHP Chinese website!