Home »
C++ STL
Copy a vector to another by using vector.assign() function in C++
C++ STL | Copy one vector to another by using vector.assign() function: Here, we are going to learn how to copy one vector to another by using vector.assign() function?
Submitted by IncludeHelp, on September 27, 2018
Problem statement
Given a vector and we have to assign copy it to another vector by using vector.assign() in C++.
Syntax
Syntax of vector.assign() function:
v2.assign(v1.begin(), v1.end());
C++ program to copy a vector to another by using vector.assign() function
#include <iostream>
#include <vector>
using namespace std;
int main() {
// declar and initialize vector 1
vector<int> v1{10, 20, 30, 40, 50};
// declare vector2
vector<int> v2(v1);
// assign all elements of v1 to v2
v2.assign(v1.begin(), v1.end());
// printing v1 and v2
cout << "v1 elements: ";
for (int i = 0; i < v1.size(); i++) {
cout << v1[i] << " ";
}
cout << endl;
cout << "v2 elements: ";
for (int i = 0; i < v2.size(); i++) {
cout << v2[i] << " ";
}
cout << endl;
return 0;
}
Output
v1 elements: 10 20 30 40 50
v2 elements: 10 20 30 40 50