By using inbuilt copy functions
copy(itBegin(),it!=end(), back_inserter()) :- first way to copy old vector into new one. This function takes 3 arguments, first, the first iterator is old vector first value, second, the last iterator of old ,Last in back_inserter. Vector V2 in empty ,so we can not use V2.begin() as a target but we have to use intserter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<iterator> | |
using namespace std; | |
int main() | |
{ | |
vector<int>v1{1,2,3,4,5}; | |
vector<int>v2; | |
cout<<"First vector size: "<<v1.size()<<endl; | |
cout<<"Second vector size :"<<v2.size()<<endl; | |
vector<int>::iterator it; | |
copy(v1.begin(),v1.end(),back_inserter(v2)); | |
cout<<"First vector size: "<<v1.size()<<endl; | |
cout<<"Second vector size :"<<v2.size()<<endl; | |
cout<<"--------------First Vector-------"<<endl; | |
for(auto &el : v1) | |
{cout<<el<<" ";} | |
cout<<endl; | |
cout<<"--------------Second Vector-------"<<endl; | |
for(auto it=v2.begin();it!=v2.end();it++) | |
{ | |
cout<<*it<<" "; | |
} | |
return 0; | |
} |
First vector size: 5 First vector size: 5 Second vector size :5 --------------First Vector------- 1 2 3 4 5 --------------Second Vector------- 1 2 3 4 5If your vector in pre initilized by some random value then you can use same above copy commend with V2.begin() inside copy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<iterator> | |
using namespace std; | |
int main() | |
{ | |
vector<int>v1{1,2,3,4,5}; | |
vector<int>v2(5,1); | |
cout<<"First vector size: "<<v1.size()<<endl; | |
cout<<"Second vector size :"<<v2.size()<<endl; | |
vector<int>::iterator it; | |
copy(v1.begin(),v1.end(),v2.begin()); | |
cout<<"First vector size: "<<v1.size()<<endl; | |
cout<<"Second vector size :"<<v2.size()<<endl; | |
cout<<"--------------First Vector-------"<<endl; | |
for(auto &el : v1) | |
{cout<<el<<" ";} | |
cout<<endl; | |
cout<<"--------------Second Vector-------"<<endl; | |
for(auto it=v2.begin();it!=v2.end();it++) | |
{ | |
cout<<*it<<" "; | |
} | |
return 0; | |
} |
First vector size: 5 First vector size: 5 Second vector size :5 --------------First Vector------- 1 2 3 4 5 --------------Second Vector------- 1 2 3 4 5
0 Comments
If you have any doubt and suggestion Please let me know