Hi, what is the quickest (most processor efficient) way of copying from one vector to another?
thanks.
Printable View
Hi, what is the quickest (most processor efficient) way of copying from one vector to another?
thanks.
Do you want to copy the entire vector, or just a part of it?
The entire vector is all I need.
I'm currently copying it all using a loop and pushing each item from the source vector to the target vector one at a time - but I'm trying to optimize my code.
thanks,
Code:#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<int> v1;
v1.push_back(10);
v1.push_back(5);
v1.push_back(9);
// You can initialize a vector from another
vector<int>v2(v1);
// You can assign a vector to another
vector<int> v3;
v3 = v2;
cout << v3[0] << ", " << v3[1] << ", " << v3[2] << endl;
// outputs: 10, 5, 9
}
If you won't need your source vector after the copy, the quickest way is to use swap because it doesn't actually copy anything.Otherwise, initialization or assignment as Darryl showed is the best way (assuming both vectors hold the same type).Code:v1.swap(v2);
that's great - thanks