Andrew Koenig said:
Your original example was
std::vector<double> v;
v.reserve(10000); // don't forget this
std::copy(ptr, ptr+10000, std::back_inserter(v));
which computes ptr+10000. You can't do that unless ptr is a random-access
iterator.
My claim is true regardless of whether you call reserve first, as long as
the only difference between the two pieces of code being compared is the
difference between
copy(ptr, ptr+10000, back_inserter(v));
and
v.insert(v.end(), ptr, ptr+10000);
If you disagree, please post a code example in which you think that the
calls to copy and back_inserter are better than the call to insert, and
explain why you think they're better.
Sorry, I see now I misunderstood your original post. It wasn't clear to me
what you were replacing, and for some reason I thought you meant the reserve
statement as well as std::copy. I should have seen about two rounds ago that
that isn't what you meant.
So let's see if we agree on this:
// version 1
std::vector<double> v(10000);
std::copy(ptr, ptr+10000, &v[0]);
// version 2
std::vector<double> v;
std::copy(ptr, ptr+10000, std::back_inserter(v));
// version 3
std::vector<double> v;
v.reserve(10000);
std::copy(ptr, ptr+10000, std::back_inserter(v));
// version 4
std::vector<double> v;
v.reserve(10000);
v.insert(v.end(), ptr, ptr+10000);
Version 1 pointlessly initializes 10000 values and then overwrites them.
Version 2 avoids that problem but reallocates memory many times. Version 3,
which is how I have been doing it, has neither of those problems but has to
check on each iteration to see if there is enough memory and perhaps do some
other useless linear time bookkeeping. Version 4, which is how I will do it
from now on, might degenerate into version 3 but might do better depending
on the implementation.
Sorry I was so thick on this one.