简体   繁体   English

从某个 position 开始将一个向量复制到另一个向量中

[英]Copying one vector into another starting at some position

Say I have two vectors假设我有两个向量

auto a = std::vector<int>{10, 11, 12, 13, 14, 15};
auto b = std::vector<int>{21, 22, 23};

and I want to copy the entire content of b into a starting at some position (let's say 4 ), possibly overriding elements and resizing the vector, so that the resulting vector a looks like我想将b的全部内容复制到a中,从 position 开始(假设为4 ),可能会覆盖元素并调整向量的大小,以便生成的向量a看起来像

[10, 11, 12, 13, 21, 22, 23]

Is there some function in the STL (maybe in <algorithm> or `) that does exactly that? STL 中是否有一些 function(可能在<algorithm>或`)中确实如此?

With the help of C++20 <ranges>借助 C++20 <ranges>

auto a = std::vector{10, 11, 12, 13, 14, 15};
auto b = std::vector{21, 22, 23};

auto pos = 4;
auto c = a | std::views::drop(pos);
auto sz = c.size();
std::ranges::copy(b | std::views::take(sz), c.begin());
std::ranges::copy(b | std::views::drop(sz), std::back_inserter(a));

Demo演示

You can do it like this:你可以这样做:

    auto a = std::vector<int>{ 10, 11, 12, 13, 14, 15 };
    auto b = std::vector<int>{ 21, 22, 23 };

    int from = 4; //from which index

    a.insert(a.begin() + from, b.begin(), b.end());
    a.resize(from + b.size());

    for (auto i : a) {
        std::cout << i << " ";
    }

There's no ready-made algorithm to do it.没有现成的算法可以做到这一点。 You can implement it yourself like this:您可以像这样自己实现它:

auto a = std::vector<int>{10, 11, 12, 13, 14, 15};
auto b = std::vector<int>{21, 22, 23};

std::size_t insertionPoint = 4;
std::size_t elemCount = std::max(insertionPoint + b.size(), a.size());
a.resize(elemCount);
std::copy(std::cbegin(b), std::cend(b), std::begin(a) + insertionPoint);

Note:笔记:

  • This requires the value type of std::vector (ie, in this case, int ) to be default constructible.这要求std::vector的值类型(即,在本例中为int )是默认可构造的。
  • If insertionPoint is greater than a.size() you'll get default constructed elements between the last element of a (before the insertion) and the first inserted element from b .如果insertionPoint大于a.size() ,您将在a的最后一个元素(插入之前)和b的第一个插入元素之间获得默认构造的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM