Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some function like std::size()?

Tags:

c++

c++11

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.

like image 241
Adrian Avatar asked Oct 08 '13 20:10

Adrian


2 Answers

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().

like image 197
Ricky65 Avatar answered Sep 23 '22 00:09

Ricky65


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; };
like image 32
Kerrek SB Avatar answered Sep 25 '22 00:09

Kerrek SB