This post will discuss how to convert a list to a vector in C++.

1. Using range-based for-loop

A naive solution is to use a range-based for-loop (or simple for-loop) to iterate the list and individually add each encountered element to an empty vector.

Download  Run Code

Output:

a b c

 
Please note that the push_back function is used to preserve the order of elements present in the list.

2. Using Range Constructor

We can also use the range constructor offered by the vector class that takes two input iterators pointing to the beginning and the end of an input sequence.

Download  Run Code

Output:

a b c

 
We can also use a move iterator to “move” all elements from the list to a vector.

Download  Run Code

Output:

a b c

3. Using std::copy function

We can use the standard algorithm std::copy to insert elements of a container into another container, as shown below:

Download  Run Code

Output:

a b c

 
As evident from the above code, the destination container needs enough space to accommodate all elements. If enough space is not available, the workaround uses insert iterators such as std::back_inserter.

Download  Run Code

Output:

a b c

That’s all about converting a list to a vector in C++.