替换向量中的子向量

888*_*888 5 c++ vector

我有

vector<int> my_vector;
vector<int> other_vector;
Run Code Online (Sandbox Code Playgroud)

my_vector.size() == 20other_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];
 }
Run Code Online (Sandbox Code Playgroud)

我已经完成了,但我想知道是否有更有效的方法来做到这一点.有什么建议吗?

(当然,数字20和5只是一个例子,在我的情况下,我有更大的尺寸!)

Naw*_*waz 7

在C++ 11中,std::copy_n添加了一个友好的函数,因此您可以使用它:

 std::copy_n(other_vector.begin(), 5, &my_vector[n]);
Run Code Online (Sandbox Code Playgroud)

在C++ 03中,您可以使用std::copy已经提到的其他答案.


Som*_*ude 5

你可以使用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);
Run Code Online (Sandbox Code Playgroud)

尽管这基本上与您的幼稚解决方案相同。

  • `std::advance(std::begin(my_vector), n)` 与 `std::begin(my_vector) + n` 相同,与 `&amp;my_vector[n]` 相同。毕竟它是向量(随机迭代器)。 (4认同)