I found the following template on a blog:
template <typename T, size_t N>
struct array_info<T[N]>
{
typedef T type;
enum { size = N };
};
It is an elegant alternative to sizeof(a) / sizeof(a[0])
.
A commonly-used construct for getting the size of an array should surely be somewhere in a library. I'm not aware of one. Can anyone tell me this functionality is in the standard libraries somewhere and/or in Boost? Preferably in an easy-to-use and lightweight form.
sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
No. In an array declaration, the size must be known at compile time. You can�t specify a size that�s known only at runtime.
array::size() size() function is used to return the size of the list container or the number of elements in the list container.
I eventually found the answer myself - boost::size()
:
#include <boost/range.hpp>
int array[10];
boost::size(array); // returns 10
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