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

1. Using Range Constructor

A simple solution is to use the range constructor of std::list, which constructs a new list initialized by elements of the specified range (defined by two input iterators).

Download  Run Code

Output:

10 15 20 25

2. Using std::insert function

For an existing list, we can use the overloaded std::insert function that takes three parameters. The first parameter is an iterator to the destination list. The second and third parameters are the iterators specifying a range of the array elements.

Download  Run Code

Output:

10 15 20 25

3. Using range-based for-loop

We can also use the range-based for-loop that loops through the array elements and adds each encountered element to the list using list::push_back.

Download  Run Code

Output:

10 15 20 25

4. Using std::copy function

Another solution is to use the std::copy, which copies the specified range of elements to another range beginning from the specified output iterator.

We can either use std::back_inserter to the initial position in the destination list that calls the push_back() function behind the scenes. If the list has enough storage, we can simply specify the output iterator to the beginning of the destination range.

Download  Run Code

Output:

10 15 20 25

5. Using std::assign function

We can also use the std::assign function that replaces the existing contents of the list with elements of the specified range.

Download  Run Code

Output:

10 15 20 25

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