convert vector into array c++
To convert a vector into an array in C++, you can follow these steps:
- Declare a vector: Start by declaring a vector and populating it with elements. For example:
#include <vector>
using namespace std;
vector<int> vec = {1, 2, 3, 4, 5};
- Declare an array: Next, declare an array with a size equal to the vector's size. For example:
int arr[vec.size()];
- Copy elements from the vector to the array: Use the
std::copy
function from the<algorithm>
header to copy elements from the vector to the array. For example:
#include <algorithm>
copy(vec.begin(), vec.end(), arr);
- Access elements in the array: You can now access the elements in the array using array indexing. For example:
for (int i = 0; i < vec.size(); i++) {
cout << arr[i] << " ";
}
This will output: 1 2 3 4 5
, which are the elements from the vector copied into the array.
That's it! You have successfully converted a vector into an array in C++.