Alex Rivera | Logout

Best way to copy a vector to a list in STL?

Asked 2009-01-19T17:46:51.680
46

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

Edit
Report

1 Answer

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.

answered 2009-01-24T04:25:23.480

Your Answer