sgowd
sgowd

Reputation: 1034

Which method is faster? back_inserter or resize

I want to copy from vector v1 of type uint into v2 of type uint.

V1 has about 750,000 elements.

Option 1:

std::copy(v1.begin(), v1.end(), std::back_inserter(v2));

or

Option 2:

v2.resize(v1.size());
std::copy(v1.begin(), v1.end(),v2.begin());

Which option would be faster? We do not use c++11.

Thank you!

Upvotes: 1

Views: 1401

Answers (2)

Mats Kindahl
Mats Kindahl

Reputation: 2060

This is a very late reply, but a few years back I did some experiments and did some measurements. They are available at my blog Copying memory from C to C++ using std::vector. It lists a few other options as well and the results might be interesting for others.

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92211

You are probably trying too hard. :-)

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

will work fine, and take care of the resize/reserve as needed.

Upvotes: 6

Related Questions