convert std vector to array

To convert a std::vector to an array in C++, you can follow these steps:

  1. Include the necessary headers: Make sure to include the <vector> and <array> headers at the beginning of your code to use the std::vector and std::array classes.
#include <vector>
#include <array>
  1. Create a std::vector: Declare and initialize a std::vector with the elements you want to convert to an array.
std::vector<int> myVector = {1, 2, 3, 4, 5};
  1. 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;
  1. Copy elements from std::vector to the array: Use the std::copy algorithm to copy the elements from the std::vector to the array.
std::copy(myVector.begin(), myVector.end(), myArray.begin());
  1. 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.