20

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):

vec2.reserve( vec1.size() );
copy(vec1.begin(), vec1.end(), vec2.begin());

While the call to vec2 sets the capacity of vector vec2, the copying of data to vec2 seems to not fill in the values from vec1 to vec2.

Replacing the copy() function with calls to push_back() works as expected.

What am I missing here?

Thanks for your help. vectest.cpp test program followed by resulting output follows.

Compiler: gcc 3.4.4 on cygwin.

Nat

/**
 * vectest.cpp
 */

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> vec1;
    vector<int> vec2;

    vec1.push_back(1);
    vec1.push_back(2);
    vec1.push_back(3);
    vec1.push_back(4);
    vec1.push_back(5);
    vec1.push_back(6);
    vec1.push_back(7);

    vec2.reserve( vec1.size() );
    copy(vec1.begin(), vec1.end(), vec2.begin());

    cout << "vec1.size()     = " << vec1.size() << endl;
    cout << "vec1.capacity() = " << vec1.capacity() << endl;

    cout << "vec1: ";
    for( vector<int>::const_iterator iter = vec1.begin(); iter < vec1.end(); ++iter ) {
        cout << *iter << " ";
    }
    cout << endl;

    cout << "vec2.size()     = " << vec2.size() << endl;
    cout << "vec2.capacity() = " << vec2.capacity() << endl;
    cout << "vec2: ";
    for( vector<int>::const_iterator iter = vec2.begin(); iter < vec2.end(); ++iter ) {
        cout << *iter << endl;
    }

    cout << endl;
}

output:

vec1.size()     = 7
vec1.capacity() = 8
vec1: 1 2 3 4 5 6 7 
vec2.size()     = 0
vec2.capacity() = 7
vec2: 
Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
natersoz
  • 1,674
  • 2
  • 19
  • 29

5 Answers5

37

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!

Martin Drozdik
  • 12,742
  • 22
  • 81
  • 146
rlbond
  • 65,341
  • 56
  • 178
  • 228
  • I think you should emphasize "member functions" in the last paragraph, I missed it first and thought "What? copy _is_ range-based!" It is a great recommendation, so we wouldn't want people to miss it :) – AzP Apr 15 '16 at 07:58
27

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>

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Heh, yup. I too was caught up on the difference at first. – GManNickG Jul 14 '09 at 23:19
  • Eureka - that worked. Not just on the posted test app but on the more complicated problem app I was having. I was avoiding the use of resize() since that adds elements where I had not intent on adding. Thanks for the education. – natersoz Jul 14 '09 at 23:34
  • 9
    You really should be using `vec2.assign` or `vec2.insert` instead... they are more optimized. – rlbond Jul 15 '09 at 01:13
  • for some reason `vec2.begin()` doesn't compile, but just `vec2` works – titus May 29 '13 at 15:10
20

Why not: vec2 = vec1; ?

EFraim
  • 12,811
  • 4
  • 46
  • 62
  • Yes, that is very good :D but it does illustrate the difference between vector's resize() and reserve(), which tripped me up for a few hours. – jkeys Jul 14 '09 at 23:04
  • This was also helpful to me, while not what I had asked, I was not aware of the copy ctor. Thanks. – natersoz Jul 14 '09 at 23:36
  • Simple and elegant. Strange how things this simple are never obvious and straightforward in C++. – NielW Jul 09 '13 at 17:47
4

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)

malat
  • 12,152
  • 13
  • 89
  • 158
etham
  • 3,158
  • 2
  • 16
  • 13
3

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.

jkeys
  • 3,803
  • 11
  • 39
  • 63