I am having a multidimensional std::array
and looking for the proper (convenient and efficient) way to find its size (in number of cells or in bytes)
size()
returns only the last dimension size (which is understood)
std::array<std::array<std::array<std::array<double, 2>, 3>, 6>, 100> my_array;
my_array.size(); // returns 100
Although the size of the array is known in compile time, I wish to avoid #define SIZE_OF_MY_ARRAY
or a global variable because, I am looking for a better way than passing the size with the array (as in "old" arrays, not std array), or informing others to use the defined term.
I also prefer no to calculate it every time.
Perhaps these 2 preferences are not possible for multidimensional array?
How can I efficiently find the overall size of my_array
? I am using c++11.
It's not too hard to write a small utility that calculates this at compile time.
template<typename T> struct arr_sz {
static constexpr std::size_t size = sizeof(T);
};
template<typename T, std::size_t N>
struct arr_sz<std::array<T, N>> {
static constexpr std::size_t size = N * arr_sz<T>::size;
};
The above should unravel a nested array definition of any practical depth, and evaluate to the size in bytes used for storing T
's, with all potential padding excluded.
An example of using it would be
std::array<std::array<std::array<std::array<double, 2>, 3>, 6>, 100> my_array;
constexpr auto sz = arr_sz<decltype(my_array)>::size;
static_assert(sz == sizeof(double) * 2 * 3 * 6 * 100, "");
That you may see live.