[英]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.