Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

like image 375
kal Avatar asked Jan 19 '09 17:01

kal


People also ask

How do I change a vector to a list?

To convert a vector to list, R provides us with as. list() function that enables us to convert the single dimensional vector structure into a list format.

How do you copy a vector to an array?

Use copy() Function to Convert a Vector to an Array The copy() method can be utilized to convert a vector to a double array so that data elements are copied to a different memory location.


3 Answers

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

std::copy( vector.begin(), vector.end(), std::back_inserter( list ) ); 
like image 150
Kasprzol Avatar answered Oct 06 '22 21:10

Kasprzol


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.

like image 44
Fred Larson Avatar answered Oct 06 '22 21:10

Fred Larson


list.assign(vector.begin(), vector.end());
like image 20
Dennis Avatar answered Oct 06 '22 20:10

Dennis