Home > Backend Development > C++ > body text

How to Efficiently Append a Vector to Itself Without a Loop?

Barbara Streisand
Release: 2024-11-09 01:23:02
Original
542 people have browsed it

How to Efficiently Append a Vector to Itself Without a Loop?

Elegant Solution for Appending a Vector to Itself

Duplicating the contents of a vector and appending them to the original vector is a common operation. However, implementing this efficiently without a loop can be challenging.

Challenge Discussion

The question highlights the limitations of std::vector::insert and std::copy for this specific task. std::vector::insert prohibits using an iterator to refer to the current vector, and std::copy triggers a segmentation fault when used in this context.

Optimal Solution

The optimal solution involves combining std::vector::resize (or std::vector::reserve) with std::copy_n. The following code demonstrates this approach:

auto old_count = xx.size();
xx.resize(2 * old_count);
std::copy_n(xx.begin(), old_count, xx.begin() + old_count);
Copy after login

Alternatively, you can use std::vector::reserve and std::back_inserter:

auto old_count = xx.size();
xx.reserve(2 * old_count);
std::copy_n(xx.begin(), old_count, std::back_inserter(xx));
Copy after login

Explanation

std::vector::resize reallocates the vector if its new size exceeds its old capacity. std::copy_n copies the specified number of elements from the beginning of the vector to a new location.

When using std::vector::reserve, std::copy_n is necessary because the end() iterator points one element past the end of the vector. This makes it invalid for insertions.

Conclusion

This solution offers a concise and efficient way to append the contents of a vector to itself without resorting to a loop-based implementation. By utilizing the resize and copy_n operations, you can achieve the desired functionality with minimal code overhead.

The above is the detailed content of How to Efficiently Append a Vector to Itself Without a Loop?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template