[英]Copy one element from a vector to another vector
Hi I would like to know how to copy one element chosen from one vector to another.嗨,我想知道如何将从一个向量中选择的一个元素复制到另一个。 So for example I have two vectors.
例如,我有两个向量。 I would want to copy the number 7 from v1 to v2 using the position of the element.
我想使用元素的 position 将数字 7 从 v1 复制到 v2。 How can that be done?
怎么可能呢? The code below moves all the elements.
下面的代码移动所有元素。 What has to b changed?
有什么需要改变的?
int main() {
vector<int> v1{ 7,6,5,4,3};
vector<int> v2;
copy(v1.begin(), v1.end(), back_inserter(v2));
cout << "v1 vector elements are : ";
for (int i=0; i<v1.size(); i++)
{
cout << v1[i] << " ";
cout << endl;
}
cout << "v2 vector elements are : ";
for (int i=0; i<v2.size(); i++)
{
cout << v2[i] << " ";
cout<< endl;
}
return 0;
}
v2.push_back(v1[i]);
will add the i
-th element of v1
to v2
.将
v1
的第i
个元素添加到v2
。
Use std::copy
when you want to copy a range of elements.当您想要复制一系列元素时,请使用
std::copy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.