Home >Backend Development >C++ >How Can You Efficiently Duplicate and Append Vector Contents Without Using Loops?
Duplicating and Appending Vector Contents Effectively
When working with vectors, it is often necessary to duplicate elements and append them to the end of the original vector. This can be tricky without using a loop.
Challenges with Iterative Solutions
Methods like std::vector::insert() are unsuitable for this task because iterators to the vector may become invalid during insertion.
A Cleaner Approach Using Resize and Copy_n
A more elegant solution involves two steps:
Here are two example implementations:
// Using resize() and copy_n() auto old_count = xx.size(); xx.resize(2 * old_count); std::copy_n(xx.begin(), old_count, xx.begin() + old_count); // Using reserve() and copy_n() via back_inserter() auto old_count = xx.size(); xx.reserve(2 * old_count); std::copy_n(xx.begin(), old_count, std::back_inserter(xx));
In either case, the original vector's size is doubled to accommodate the duplicates, and a copy_n() operation is used to transfer the elements. It's important to remember the original vector size before resizing and using reserve() with copy_n(), as the end() iterator points past the end of the vector after reallocation.
The above is the detailed content of How Can You Efficiently Duplicate and Append Vector Contents Without Using Loops?. For more information, please follow other related articles on the PHP Chinese website!