将 std::vector 的一部分替换为更小的 std::vector

Replacing part of std::vector by smaller std::vector

我想知道用另一个较小的 std::vector 替换(覆盖)给定 std::vector“输入”的一部分的正确方法是什么? 我确实需要保持原始矢量的其余部分不变。 我也不需要打扰原始向量中的内容和 之后我不需要再保留较小的向量了。

假设我有这个:

std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6, 7, 8 };

我想实现:

input = { 1, 2, 3, 4, 5, 6, 7, 8, 99}

正确的做法是什么?我想到了类似

input.replace(input.beginn(), input.beginn()+a.size(), a);
// intermediate input would look like that: input = { 1, 2, 3, 1, 2, 22, 3, 33, 99 };

input.replace(input.beginn()+a.size(), input.beginn()+a.size()+b.size(), b);

应该有一个标准的方法来做,不是吗? 到目前为止,我对此的想法如下:

另外,如果解决方案不会因不必要的清除或将值写回到向量 a 或 b 中而浪费性能,我更愿意这样做。我的矢量实际上会非常大,这最终是关于性能的。

非常感谢任何能干的帮助。

试试这个:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
    std::vector<int> a = { 1, 2, 3 };
    std::vector<int> b = { 4, 5, 6, 7, 8 };

    std::set_union( a.begin(), a.end(), b.begin(), b.end(), input.begin() );

    for ( std::vector<int>::const_iterator iter = input.begin();
          iter != input.end();
          ++iter )
    {
        std::cout << *iter << " ";
    }

    return 0;
}

它输出:

1 2 3 4 5 6 7 8 99 

你似乎在 std::copy(). This is how you would use it in your example (live demo on Coliru):

#include <algorithm> // Necessary for `std::copy`...

// ...

std::vector<int> input = { 0, 0, 1, 1, 2, 22, 3, 33, 99 };
std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6, 7, 8 };    

std::copy(std::begin(a), std::end(a), std::begin(input));
std::copy(std::begin(b), std::end(b), std::begin(input) + a.size());

正如 Zyx2000 注释 ,在这种情况下,您还可以使用第一次调用 std::copy() 返回的迭代器作为下一个副本的插入点:

auto last = std::copy(std::begin(a), std::end(a), std::begin(input));
std::copy(std::begin(b), std::end(b), last);

这样,就不再需要随机访问迭代器了——当我们有表达式 std::begin(input) + a.size().

时就是这种情况

std::copy() 的前两个参数表示要复制的元素的源范围。第三个参数是目标容器中要覆盖的第一个元素的迭代器。

使用 std::copy() 时,请确保目标容器足够大以容纳您要复制的元素数。

此外,源和目标范围不应交错。