convert std vector to array
To convert a std::vector
to an array in C++, you can follow these steps:
- Include the necessary headers: Make sure to include the
<vector>
and<array>
headers at the beginning of your code to use thestd::vector
andstd::array
classes.
#include <vector>
#include <array>
- Create a
std::vector
: Declare and initialize astd::vector
with the elements you want to convert to an array.
std::vector<int> myVector = {1, 2, 3, 4, 5};
- Declare an array: Declare an array of the desired type and size. The size of the array should be equal to the size of the
std::vector
.
std::array<int, 5> myArray;
- Copy elements from
std::vector
to the array: Use thestd::copy
algorithm to copy the elements from thestd::vector
to the array.
std::copy(myVector.begin(), myVector.end(), myArray.begin());
- Access the array elements: Now, you can access the elements of the array just like any other array.
for (int i = 0; i < myArray.size(); i++) {
std::cout << myArray[i] << " ";
}
The complete code would look like this:
#include <iostream>
#include <vector>
#include <array>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
std::array<int, 5> myArray;
std::copy(myVector.begin(), myVector.end(), myArray.begin());
for (int i = 0; i < myArray.size(); i++) {
std::cout << myArray[i] << " ";
}
return 0;
}
This code will convert the std::vector
to an array and output the elements of the array.