Greetings,
I am trying to perform a copy from one vector (vec1) to another vector (vec2) using the following 2 abbreviated lines of code (full test app follows):
Change reserve to resize():
vec2.resize(vec1.size(), '\0');
copy(vec1.begin(), vec1.end(), vec2.begin());
I believe that is the fix you need.
I can't give you a very good description on the difference, but basically reserve() makes sure you have enough space, and resize() actually inserts something in there.
As noted in other answers and comments, you should just use vector's built-in functionality for this. But:
When you reserve()
elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back()
because the memory is already allocated.
When you resize()
the vector, it will allocate enough space for those elements, but also add them to the vector.
So if you resize a vector to 100, you can access elements 0 - 99, but if you reserve 100 elements, they are not inserted yet, just ready to be used.
What you want is something like this:
vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), std::back_inserter(vec2));
std::back_inserter is defined in <iterator>
If the vectors are of the same type, use copy construction or copy assignment:
vec2(vec1);
vec2 = vec1;
If the vectors aren't the exact same (maybe a different allocator or something, or vec1 is a deque), what you really want is the range-based constructor or range-based assign:
vec2(vec1.begin(), vec1.end()); // range-based constructor
vec2.assign(vec1.begin(), vec1.end()); // range-based assignment
If you insist on doing it with std::copy
, the proper method is:
copy(vec1.begin(), vec1.end(), back_inserter(vec2));
Since reserving the space does not make it assignable. copy
works by assigning each element to its new value. So vec2.size()
needs to be at least as large as vec1.size()
in your case. Calling reserve
doesn't actually change a vector's size, just its capacity.
In the book Effective STL, Scott Meyers argues that nearly all uses of std::copy for insertion should be replaced with range-based member functions. I suggest you pick up a copy, it's a great reference!
Why not: vec2 = vec1;
?
In my opinion, the simplest way is to use the std::vector::insert
method:
v2.insert(v2.end(), v1.begin(), v1.end());
(see std::vector::insert)