Home
Aptitude
Categories


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

Given a vector and we have to assign copy it to another vector by using vector.assign() in C++.

Syntax of vector.assign() function:

    v2.assign(v1.begin(), v1.end());

Program:

#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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.