copy w/ back_inserter vs. container<T> c(b,e)

I'm using Koenig/Moo's Accelerated C++, chapter 6, "Using library algorithms". This is invalid code:

1
2
3
vector<int> u(10, 100);
vector<int> v;
copy(u.begin(), u.end(), v.begin());

Exercise 6.4 asks,

There are at least two possible ways to correct the program. Implement both, and describe the relative advantages and disadvantages of each approach.

The two ways (I believe) are simply:

1
2
3
vector<int> u(10, 100);
vector<int> v;
copy(u.begin(), u.end(), back_inserter(v));
and
1
2
vector<int> u(10, 100);
vector<int> v(u.begin(),u.end());

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!
Looking further, there is a third option:

1
2
vector<int> u(10,100);
vector<int> v(u);


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.

Am I getting closer?
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).

The first correct version would be:
1
2
std::vector<int> v(u.size());
std::copy(u.begin(), u.end(), v.begin());

The second correct version would be:
1
2
3
std::vector<int> v();
v.resize(u.size());
std::copy(u.begin(), u.end(), v.begin());


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;
Last edited on
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).

Topic archived. No new replies allowed.