Apologies in advance for the Vehicle class. There's no good reason why it's templated. I was just curious how to create a templated class that can be appended to an ostream.
The crux of the problem is that I want to use std::copy to copy Vehicle objects from a populated vector (cars) to an empty vector (copy_cars).
If I replace copy_cars.begin() with back_inserter(copy_cars), per advice from [1], the code works as expected. What is copy() expecting as the third argument and why isn't copy_cars.begin() suitable?
In pseudocode, std::copy is basically just doing this:
1 2 3 4 5
copy( first, last, dest_first )
{
while( first != last ) *dest_first++ = *first++;
return dest_first;
}
Note that it does not allocate additional memory in the destination container but expects the memory to already be allocated. If you first sized the destination container to be the correct size it would work. Alternatively, by passing back_inserter(...) the iterator will be such that the *dest_first operation will extend the size of the container before copying the source element.
Apparently, reserving storage (increasing a vector's capacity) via vector.reserve() isn't sufficient. For std::copy to work, there needs to be elements in the vector.