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

1. Using Range Constructor

The idea is to pass two input iterators pointing to the beginning and end of the given vector to the range constructor of the list class. This is a very effective, simple, short, and clear approach.

Download  Run Code

Output:

1 2 3 4 5

2. Using std::copy function

If we need to copy elements of a vector to an existing list, the efficient solution is to use the standard algorithm std::copy, which inserts the elements of a source sequence into a destination container with the output iterator.

The output iterator is usually the iterator to the initial position in the destination container. The destination container should have sufficient space to accommodate elements of the source sequence. However, if this is not the case, the workaround uses insert iterators like std::back_inserter, which internally calls the push_back function on the destination container.

Download  Run Code

Output:

1 2 3 4 5

3. Using std::list::insert function

We can also use the insert() function of the list class, which takes a starting position in the list for inserting the new elements and two input iterators pointing to the range of elements in the source sequence.

Download  Run Code

Output:

1 2 3 4 5

4. Using std::list::assign function

We can also overwrite existing elements in the list container with new elements in the specified range with the help of the assign() function of the list class.

Download  Run Code

Output:

1 2 3 4 5

5. Naive Solution

Finally, we can even write our own routine for converting vector to a list. We create an empty list, traverse the vector using for-loop, and insert every element into the list. Starting C++11, the range-based for-loop, is the most elegant way to traverse any container.

Download  Run Code

Output:

1 2 3 4 5

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