Given a builtin array x of arbitrary type T, there are functions std::begin() and std::end() that I can call, but why isn't there a std::size()? Seems odd not to have that.
I could use std::end(x)-std::begin(x), but still a std::size(x) would be better.
Yes, I know of the std::vector and std::array classes. This is just a question of why something as simple as this isn't available as yet in the STL.
Just a note to let people know that N4280 "Non-member size() and more (Revision 2)" has been accepted into the C++17 Working Draft. This includes std::size() as well as std::empty() and std::data().
There's std::extent, which is to be applied to the type of the array:
#include <type_traits>
int a[12];
assert(std::extent<decltype(a)>::value == 12);
Alternatively you can use std::distance(std::begin(a), std::end(a)).
The former is manifestly a constant expression, though in practice the latter can be comuted statically as well.
Finally, there's always the homegrown solution:
template <typename T, std::size_t N>
constexpr std::size_t array_size(T const (&)[N])
{ return N; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With