簡體   English   中英

從某個 position 開始將一個向量復制到另一個向量中

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

假設我有兩個向量

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

我想將b的全部內容復制到a中,從 position 開始(假設為4 ),可能會覆蓋元素並調整向量的大小,以便生成的向量a看起來像

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

STL 中是否有一些 function(可能在<algorithm>或`)中確實如此?

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

演示

你可以這樣做:

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

沒有現成的算法可以做到這一點。 您可以像這樣自己實現它:

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

筆記:

  • 這要求std::vector的值類型(即,在本例中為int )是默認可構造的。
  • 如果insertionPoint大於a.size() ,您將在a的最后一個元素(插入之前)和b的第一個插入元素之間獲得默認構造的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM