Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner to convert from list<T> to vector<T>

Tags:

c++

stl

Is there an one-liner that converts a list<T> to vector<T>?

A google search returns me a lot of results that use manual, lengthy conversion, which make me puke. Should we go to that much trouble to do something as simple as a list-to-vector conversion?

like image 223
Graviton Avatar asked Mar 07 '11 10:03

Graviton


People also ask

How do I turn a list into a vector?

To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.

When should I use vector instead of list?

If you don't need to insert elements often then a vector will be more efficient. It has much better CPU cache locality than a list. In other words, accessing one element makes it very likely that the next element is present in the cache and can be retrieved without having to read slow RAM.


1 Answers

You can only create a new vector with all the elements from the list:

std::vector<T> v{ std::begin(l), std::end(l) }; 

where l is a std::list<T>. This will copy all elements from the list to the vector.

Since C++11 this can be made more efficient if you don't need the original list anymore. Instead of copying, you can move all elements into the vector:

std::vector<T> v{ std::make_move_iterator(std::begin(l)),                    std::make_move_iterator(std::end(l)) }; 
like image 189
Björn Pollex Avatar answered Oct 08 '22 02:10

Björn Pollex