44

Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?

kal
  • 28,545
  • 49
  • 129
  • 149

5 Answers5

90

Why would you iterate and not use the standard copy algorithm?

std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );
Doug T.
  • 64,223
  • 27
  • 138
  • 202
Kasprzol
  • 4,087
  • 22
  • 20
  • Should be std::copy rather than stl::copy, but otherwise this is the preferred method when using iterators to copy. – workmad3 Jan 19 '09 at 17:57
70

If you're making a new list, you can take advantage of a constructor that takes begin and end iterators:

std::list<SomeType> myList(v.begin(), v.end());

Kasprzol's answer is perfect if you have an existing list you want to append to.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • Is it faster than std::copy( vector.begin(), vector.end(), std::back_inserter( list ) ); ? What's the difference under the hood? – Kornel Szymkiewicz Apr 13 '18 at 20:17
  • I doubt it would be any slower, and it may be able to optimize things a bit better. Standard library implementations vary, so it's hard to say for sure. Profile it if it's important to you. – Fred Larson Apr 13 '18 at 20:21
10
list.assign(vector.begin(), vector.end());
Dennis
  • 56,821
  • 26
  • 143
  • 139
  • This is helpful, but you should probably add some non-code to this answer to avoid a potential VLQ flag. – Keith M Oct 04 '16 at 18:44
3

I like this suggestion for constructing a new list.

std::list<SomeType> myList(v.begin(), v.end());

But when appending to an existing list, the following may be optimal for small data sets. By "optimal", I mean that it is easiest to remember how to do and easiest to understand. (These are subjective statements, I'm sure it depends on how your brain is wired.)

for ( unsigned i=0; i<v.size(); i++ ) myList.push_back(v[i]);

Using iterators on vectors may be overly pedantic in many cases. Simple indexing usually works fine.

Another thread addresses iterators vs. indices (here). In that thread, the taken answer basically preferred iterators because they are more generic. But if vectors are the most commonly used container type, I think it is reasonable to specialize this kind of simple algorithm.

Community
  • 1
  • 1
0

You can try to use trickier things from the <algorithm> header, for example for_each or copy ... but they would amount to the same thing, in my opinion.

ChrisW
  • 54,973
  • 13
  • 116
  • 224
  • for_each will amount to the same. Copy can be overloaded to provide much more efficient copy mechanics depending on the iterators provided, and is generally the preferred mechanism. – workmad3 Jan 19 '09 at 17:58