Does the iterator adaptor back_inserter have more overhead than doing it at definition? Is the back_inserter only useful when you don't yet have the necessary iterators at the definition? If you do have the necessary iterators, then the latter solution is, apparently, more elegant.
I'm not doing this for a class but slogging through this on my own, if that makes any difference.
Thanks for all the help; you folks have been great!
More elegant still. This is the best option, then unless you only want to copy a subset then option #2 with iterators is better and then use #3 with the iterator adaptor if you don't know the iterators at the time of definition.
The original snippet is incorrect because std::copy() needs the destination container to be at least as big as the source container.
Your first correction is over-thought (and slow).
Your third snippet is usually the best. The best use of std::copy() is for things that don't have copy constructors or overloaded assignment operators, such as arrays.
Note that line 2 could be rewritten as vector<int> v=u;
The copy constructor is the fastest (others may or may not be as fast; probably not).
Only one memory allocation is needed in the copy constructor case. With iterator adaptors, potentially several allocations/deallocations occur as the vector is resized. With the template constructor, you'd have to look at the implementation to see if a std::distance() is used to pre-allocate an array large enough. (std::distance on random access iterators should be O(1) since a simple subtraction can be used).