Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.
Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header
.
std::rank
If T
is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.
std::extent
If T
is an array type, provides the member constant value equal to the number of elements along the N
th dimension of the array, if N
is in [0, std::rank
). For any other type, or if T
is array of unknown bound along its first dimension and N
is 0, value is 0.
std::remove_extent
If T
is an array of some type X
, provides the member typedef type equal to X
, otherwise type is T
. Note that if T
is a multidimensional array, only the first dimension is removed.
std::remove_all_extents
If T
is a multidimensional array of some type X
, provides the member typedef type equal to X
, otherwise type is T
.
To get the length on any dimension of a multidimential array, decltype
could be used to combine with std::extent
. For example:
#include
#include // std::remove_extent std::remove_all_extents std::rank std::extent
template
constexpr size_t length(T(&)[N]) { return N; }
template
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
// New way
constexpr auto l1 = std::extent::value; // 5
constexpr auto l2 = std::extent::value; // 4
constexpr auto l3 = std::extent::value; // 3
constexpr auto l4 = std::extent::value; // 0
// Mixed way
constexpr auto la = length(a);
//constexpr auto lpa = length(*a); // compile error
//auto lpa = length(*a); // get at runtime
std::remove_extent::type pa; // get at compile time
//std::remove_reference::type pa; // same as above
constexpr auto lpa = length(pa);
std::cout << la << ' ' << lpa << '\n';
// Old way
constexpr auto la2 = sizeof(a) / sizeof(*a);
constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
std::cout << la2 << ' ' << lpa2 << '\n';
return 0;
}
BTY, to get the total number of elements in a multidimentional array:
constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents::type);
Or put it in a function template:
#include
#include
template
constexpr size_t len(T &a)
{
return sizeof(a) / sizeof(typename std::remove_all_extents::type);
}
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
constexpr auto ttt = len(a);
int i;
std::cout << ttt << ' ' << len(i) << '\n';
return 0;
}
More examples of how to use them could be found by following the links.