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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…