I am trying to build a std::array
from the data of a std::vector
. I have currently done this :
#include <vector>
#include <array>
int main(void)
{
std::vector<int> vec{{1, 2, 3, 4, 5}};
std::array<int, 5> arr{static_cast<int [5]>(vec.data())};
(void)arr;
return 0;
}
but gcc does not accept this cast :
error: invalid static_cast from type ‘int*’ to type ‘int [5]’
I thought an array could be used as a pointer so why cannot we do this cast ?
Edit: This is not a duplicate of Copy std::vector into std::array since my question is about initialization (construction) of an std::array
; not copy into it.
Edit: I have done this :
#include <vector>
#include <array>
int main(void)
{
std::vector<int> vec{{1, 2, 3, 4, 5}};
int *a(vec.data());
std::array<int, 5> arr{*reinterpret_cast<int (*)[5]>(&a)};
(void)arr;
return 0;
}
But array does not initialize... gcc says :
error: array must be initialized with a brace-enclosed initializer
int*
to aint[5]
? – Chieldata()
method of the vector. If it is not possible, what is the reason ? – Boiethios