Nice way to append a vector to itself(将向量附加到自身的好方法)
问题描述
我想复制向量的内容,并希望将它们附加到原始向量的末尾,即 v[i]=v[i+n] for i=0,2,...,n-1
I want to duplicate the contents of the vector and want them to be appended at the end of the original vector i.e. v[i]=v[i+n] for i=0,2,...,n-1
我正在寻找一种很好的方式来做到这一点,而不是使用循环.我看到了 std::vector::insert
但迭代版本禁止迭代器到 *this
(即行为未定义).
I am looking for a nice way to do it, not with a loop. I saw std::vector::insert
but the iterative version forbids a iterator to *this
(i.e behaviour is undefined).
我也尝试了 std::copy
如下(但它导致了分段错误):
I also tried std::copy
as follows(but it resulted in segmentation fault):
copy(xx.begin(), xx.end(), xx.end());
推荐答案
哇.这么多接近的答案,没有一个是正确的.您需要resize
(或reserve
)和copy_n
,同时记住原始大小.
Wow. So many answers that are close, none with all the right pieces. You need both resize
(or reserve
) and copy_n
, along with remembering the original size.
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()
迭代器指向最后一个元素......这意味着它也不是第一次插入的插入点之前",变为无效.
When using reserve
, copy_n
is required because the end()
iterator points one element past the end... which means it also is not "before the insertion point" of the first insertion, and becomes invalid.
23.3.6.5 [vector.modifiers]
承诺 insert
和 push_back
:
23.3.6.5 [vector.modifiers]
promises that for insert
and push_back
:
备注: 如果新容量大于旧容量,则导致重新分配.如果没有发生重新分配,插入点之前的所有迭代器和引用都保持有效.如果异常不是由 T 的复制构造函数、移动构造函数、赋值运算符或移动赋值运算符引发的,或者由任何 InputIterator 操作都没有效果.如果非 CopyInsertable T 的移动构造函数抛出异常,则影响未指定.
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.
这篇关于将向量附加到自身的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将向量附加到自身的好方法


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30