[英]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>
或`)中確實如此?
你可以這樣做:
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.