猿问

向其自身附加向量的好方法

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


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


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


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


慕仙森
浏览 384回答 3
3回答

慕村225694

我会这样做:#include <algorithm>#include <vector>#include <utility>int main(int argc, char* argv[]){&nbsp; &nbsp; std::vector<int> v1 = { 1, 2, 3, 4, 5 };&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; std::vector<int> v2(v1.begin(), v1.end());&nbsp; &nbsp; &nbsp; &nbsp; std::copy(v1.begin(), v1.end(), std::back_inserter(v2));&nbsp; &nbsp; &nbsp; &nbsp; std::swap(v1, v2);&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}编辑:我添加了一个稍微更有效的版本。#include <algorithm>#include <vector>#include <utility>int main(int argc, char* argv[]){&nbsp; &nbsp; std::vector<int> v1 = { 1, 2, 3, 4, 5 };&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; typedef std::move_iterator<decltype(v1)::iterator> VecMoveIter;&nbsp; &nbsp; &nbsp; &nbsp; std::vector<int> v2(v1);&nbsp; &nbsp; &nbsp; &nbsp; std::copy(VecMoveIter(v1.begin()), VecMoveIter(v1.end()), std::back_inserter(v2));&nbsp; &nbsp; &nbsp; &nbsp; v1 = std::move(v2);&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}

犯罪嫌疑人X

用于附加多个副本插槽。&nbsp; &nbsp; int main() {&nbsp; &nbsp; &nbsp; &nbsp; std::vector<int> V;&nbsp; &nbsp; &nbsp; &nbsp; V.push_back(1);&nbsp; &nbsp; &nbsp; &nbsp; V.push_back(2);&nbsp; &nbsp; &nbsp; &nbsp; int oldSize = V.size();&nbsp; &nbsp; &nbsp; &nbsp; int newSize = oldSize;&nbsp; &nbsp; &nbsp; &nbsp; int nDupSlot = 4;&nbsp; &nbsp; &nbsp; &nbsp; V.resize(nDupSlot * oldSize);&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0; i<(nDupSlot-1); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::copy_n(V.begin(), oldSize, V.begin() + newSize);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newSize = newSize + oldSize;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; for(int i =0; i<V.size(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout<<V[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }输出:12121212
随时随地看视频慕课网APP
我要回答