Convert a vector to an array in C++
This post will discuss how to convert a vector to an array in C++.
1. Using std::copy algorithm
A simple way to convert a vector to an array in C++ is to use the standard algorithm copy() from the <algorithm> header. This algorithm copies the elements from one range to another range, preserving the order and the values of the elements. To use the copy algorithm to convert a vector to an array, we need to provide three arguments: the beginning and the end of the source range (the vector), and the beginning of the destination range (the array). For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> input({ 1, 2, 3, 4, 5 }); int arr[input.size()]; std::copy(input.begin(), input.end(), arr); for (int i: arr) { std::cout << i << ' '; // 1 2 3 4 5 } return 0; } |
The copy() algorithm is very safe and reliable to use, but it requires us to create an array with the same size as the vector before copying the elements.
2. Custom Solution
Another way to convert a vector to an array is to write a custom routine. The idea is to declare the array and allocate its memory large enough to hold all vector elements. Then we can use a traditional for loop to iterate over the array and set each element to the next available position in the array. Here is an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> int main() { std::vector<int> input({ 1, 2, 3, 4, 5 }); int n = input.size(); int arr[n]; for (int i = 0; i < n; i++) { arr[i] = input[i]; } for (int i: arr) { std::cout << i << ' '; // 1 2 3 4 5 } return 0; } |
That’s all about converting a vector 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 :)