gpt4 book ai didi

c++ - 将 vector 附加到自身的好方法

转载 作者:IT老高 更新时间:2023-10-28 21:46:19 26 4
gpt4 key购买 nike

我想复制 vector 的内容并希望将它们附加到原始 vector 的末尾,即 v[i]=v[i+n] for i=0,2,... ,n-1

我正在寻找一种很好的方法来做到这一点,而不是循环。我看到 std::vector::insert 但迭代版本禁止 *this 的迭代器(即行为未定义)。

我也尝试了 std::copy 如下(但它导致段错误):

copy(xx.begin(), xx.end(), xx.end());

最佳答案

哇。如此多的答案很接近,没有一个是正确的。您需要 resize(或 reserve)和 copy_n,同时记住原始大小。

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

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

当使用 reserve 时,copy_n 是必需的,因为 end() 迭代器指向末尾的一个元素...这意味着它也不是第一次插入的“插入点之前”,会失效。


23.3.6.5 [vector.modifiers] promise 对于 insertpush_back:

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. If an exception is thrown by the move constructor of a non-CopyInsertable T, the effects are unspecified.

关于c++ - 将 vector 附加到自身的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com