I have a const float* pointing to a huge array, and would like to be able to access the elements through a std::array. What is the best way to do this? Without copying the elements if possible.
Thanks!
In order to use std::array
, you need to know the size of the array at compile time. You create an empty array and use std::copy
to copy the elements into the array.
If the code which uses your const float*
only knows that size at runtime, then you cannot use std::array
but have to use std::vector
. std::vector
has a constructor to which you can pass pointers to the begin and end of the range to copy into it.
Note that in both cases, the container owns a copy of the original elements.
Without copying the elements if possible.
No, that is not possible. C++ standard containers are designed to own their contents, not just representing a view into them.
Here is an example to illustrate the difference:
#define SIZE 10 // let's assume some C or legacy code which uses macros
// ...
void f(const float* arr)
{
// size is known at compile time
std::array<float, SIZE> a;
std::copy(arr, arr + SIZE, begin(a));
}
void g(const float* arr, int size)
{
// size is only known at runtime
std::vector<float> v(arr, arr + size);
}