替换向量中的子向量

8

I have

vector<int> my_vector;
vector<int> other_vector;

使用 my_vector.size() == 20other_vector.size() == 5

给定 int n,且满足 0 < n < 14,我想要用 other_vector 替换子向量 (my_vector[n], myvector[n+1], ..., myvector[n+4])。

当然,这是一个愚蠢的代码。

 for(int i=0; i<5; i++)
 {
      my_vector[n+i] = other_vector[i];
 }

我完成了,但我在想是否有更有效的方法来完成它。 有什么建议吗?
(当然,数字20和5只是一个例子,在我的情况下,我有更大的规模!)
3个回答

9
在C++11中,添加了一个友元函数std::copy_n,因此您可以使用它:
 std::copy_n(other_vector.begin(), 5, &my_vector[n]);

在C++03中,你可以像其他答案已经提到的那样使用std::copy

1
std::next(my_vector.begin(), n)怎么样(或者只是my_vector.begin()+n)。我知道这没什么关系,但是&my_vector[n]一直看起来像是hack(这就是为什么我完全支持std::vector::data())。 - Christian Rau
@ChristianRau:它们都同样好。实际上,还有更多:std::advance(std::begin(v), n)std::begin(v) + n。但是所有这些都会占用编辑器中的水平空间,有时需要您横向滚动。因此,如果是一个向量(通常情况下),我更喜欢简短而易于理解的语法&v[i] - Nawaz

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);

尽管基本上与您的朴素解决方案相同。

4
std::advance(std::begin(my_vector), n) 相当于 std::begin(my_vector) + n,也相当于 &my_vector[n]。毕竟它是一个 vector(随机迭代器)。 - Nawaz
auto first = std::advance(std::begin(my_vector), n); doesn't work for me, I need to change it to vector<int>::iterator first = my_vector.begin(); and advance(first , n); - keineahnung2345
@keineahnung2345 你可能正在使用一个非常老的编译器,它不支持C++11标准? - Some programmer dude
@Someprogrammerdude 我使用在线编译器,这是我的代码链接:https://ideone.com/X1oyco,你能帮我检查一下吗?谢谢。 - keineahnung2345

2

我不知道性能如何,但更加简洁的版本可以使用std::copy

std::copy(other_vector.begin(),other_vector.end(),my_vector.begin()+n);

为了获得最佳性能,也许 memcpy 是答案...
memcpy(my_vector.begin()+n, other_vector.begin(), sizeof(int) *other_vector.size());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接