Hey all,

I've a couple of large enough vectors in my code, talking about 88200+ floats per vector.
I wanna copy the contents of one into the other.

I've read around, some say

vector.swap ( otherVector );

is fastest?

Currently I'm using the following:

for(int i =0; i < vector.size(); i++) { 
    vector[i] = otherVector[i];
}

I'm pretty sure thats awful in a performance sense ;-)
Let me know if there are fast ways to do this please!
Cheers, -Harry

I've read around, some say

vector.swap ( otherVector );

is fastest?

Typically, but that's not a copy operation.

Let me know if there are fast ways to do this please!

If performance is an issue, it's often better to think squiggly. Instead of making a copy, can get you get away with straight aliasing? You might not need to do any copying at all.

Another option is lazy copying such that only the modified elements of the second vector are copied. Unless all of the elements are going to be modified, lazy methods will save both time and space.

Before you spend too much time trying to find faster ways of copying vectors, you might give some thought to whether (and, if so, why) copying is a significant part of your program's total execution time.

After all, if you're copying a vector, presumably you need two copies, so you're doing something different to one copy than you are to the other. Are you sure that whatever else you're doing to those vectors isn't going to take longer than copying them? After all, copying is just about the simplest operation one can imagine. So if it's really the performance bottleneck, maybe you can rethink your algorithm to avoid it altogether.

What about the vector class' built-in copy constructor? I don't know exactly how it works, but the STL is usually pretty quick...

vector<type> copyVector(originalVector);

Or the built-in assignment operator?

vector<int> vecOne(10,0);
vector<int> vecTwo(20,0);

vecOne = vecTwo;

Both of these, of course, would require the the dataType stored in the vector have a proper copy constructor defined (which a float should). That's some massive memory usage though. Is it really that necessary?

Edited 5 Years Ago by Fbody: n/a

>What about the vector class' built-in copy constructor? I don't
>know exactly how it works, but the STL is usually pretty quick...

It works about how you would expect it to work. ;)

This article has been dead for over six months. Start a new discussion instead.