Home >Backend Development >C++ >How to Efficiently Duplicate and Append a Vector to Itself?

How to Efficiently Duplicate and Append a Vector to Itself?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 01:53:13700browse

How to Efficiently Duplicate and Append a Vector to Itself?

Efficient Vector Self-Appending

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:

  1. Resize: Extend the capacity of the vector to accommodate the duplicated elements. You can use either resize or reserve for this purpose.
  2. Copy: Use std::copy_n to transfer the original elements to the newly allocated portion of the vector.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn