maany
maany

Reputation: 31

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

Upvotes: 1

Views: 621

Answers (1)

cigien
cigien

Reputation: 60208

v2.push_back(v1[i]);

will add the i-th element of v1 to v2.

Use std::copy when you want to copy a range of elements.

Upvotes: 1

Related Questions