简体   繁体   中英

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

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

Is there some function in the STL (maybe in <algorithm> or `) that does exactly that?

With the help of 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.
  • 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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