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

1. Using Range-based for-loop

A simple solution is to use a range-based for-loop to traverse the list and, one by one, add each element at the next available index in the array. For example, if we want to convert the list {1, 2, 3, 4, 5} to an array of the same type and size, we can do something like this:

Download  Run Code

2. Using std::copy algorithm

We can also use the STL algorithm std::copy from the <algorithm> header to insert elements of a container into another container. It copies the range of elements from container to another container, preserving the order and the values of the elements. The destination container needs to have enough space to accommodate all elements. Therefore, we would need create an array with the same size as the list before copying the elements. For example:

Download  Run Code

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