Convert a list to an array in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <list> int main() { std::list<int> list = { 1, 2, 3, 4, 5 }; int arr[list.size()]; int k = 0; for (auto &i: list) { arr[k++] = i; } for (auto &i: arr) { std::cout << i << ' '; // 1 2 3 4 5 } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> #include <list> int main() { std::list<int> list = { 1, 2, 3, 4, 5 }; int arr[list.size()]; std::copy(list.begin(), list.end(), arr); for (int const &i: arr) { std::cout << i << ' '; // 1 2 3 4 5 } return 0; } |
That’s all about converting a list to an array in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)