我有
vector<int> my_vector;
vector<int> other_vector;
用my_vector.size() == 20和other_vector.size() == 5.
鉴于int n,有0 < n < 14,我想换成子矢量(my_vector[n],myvector[n+1],...,myvector[n+4]以)other_vector.
肯定有愚蠢的代码
 for(int i=0; i<5; i++)
 {
      my_vector[n+i] = other_vector[i];
 }
我已经完成了,但我想知道是否有更有效的方法来做到这一点.有什么建议吗?
(当然,数字20和5只是一个例子,在我的情况下,我有更大的尺寸!)
在C++ 11中,std::copy_n添加了一个友好的函数,因此您可以使用它:
 std::copy_n(other_vector.begin(), 5, &my_vector[n]);
在C++ 03中,您可以使用std::copy已经提到的其他答案.
你可以使用std::copy:
// Get the first destination iterator
auto first = std::advance(std::begin(my_vector), n);
// Do the copying
std::copy(std::begin(other_vector), std::end(other_vector), first);
尽管这基本上与您的幼稚解决方案相同。