Home > Enterprise >  Copying one vector into another starting at some position
Copying one vector into another starting at some position

Time:04-29

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?

CodePudding user response:

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 << " ";
    }

CodePudding user response:

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 (i.e., 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.

CodePudding user response:

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

  • Related