15

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.

paperjam
  • 8,321
  • 12
  • 53
  • 79
  • There is the standard function `_countof` (you need its template version), but I cannot find the appropriate header at the moment. – Vlad Nov 24 '11 at 13:35
  • @Vlad `_countof` is nonstandard, see https://stackoverflow.com/questions/4415530/equivalents-to-msvcs-countof-in-other-compilers – lisyarus Mar 16 '18 at 12:37

5 Answers5

27

I eventually found the answer myself - boost::size():

#include <boost/range.hpp>

int array[10];
boost::size(array); // returns 10

Although, these days you should probably use std::size() instead (since C++17)

paperjam
  • 8,321
  • 12
  • 53
  • 79
4

In the new C++ standard, std::array from the header has the method size(), which returns a constexpr and is therefore available at compile time.

You should be able to to something like

std::array< YourType, N > arr;
constexpr auto totalSize = arr.size() * sizeof( std::array< YourType, N >::value_type );

Hope this helps...

Sh4pe
  • 1,800
  • 1
  • 14
  • 30
3

C++ 17 support std::size() (defined in header <iterator>)

#include <iterator>

int my_array[10];
std::size(my_array);

std::vector<int> my_vector(10);
std::size(my_vector);
KindDragon
  • 6,558
  • 4
  • 47
  • 75
1

If possible, I would also recommend std::array or boost::array if possible. That said, you can also use boost::extent to obtain the array sizes, and boost::remove_all_extents to obtain the actual type.

In c++11, the type traits are also available in the standard library.

Edit: If your looking for a function that operates on variables, instead of types, try the following

template <typename T, std::size_t N>
std::size_t array_count(const T(&) [N]) { return N; }

See an example of use at http://ideone.com/IOdfp

Dave S
  • 20,507
  • 3
  • 48
  • 68
  • `boost::extent` seems to work on types, not objects. I need something that works on an array object, e.g. `v` in `char *v[] = {/*...*/}` – paperjam Nov 24 '11 at 16:37
-1

You need perhaps the macro _countof. According to http://www.cplusplus.com/forum/beginner/54241/, it's #defined in <cstdio>. But I am not sure if it's available outside Visual C++.

Anyway, it's not complicated to create a header file and put your definition there.


Update:
_countof is Microsoft-specific, but there is a discussion about other compilers here: Equivalents to MSVC's _countof in other compilers?

Community
  • 1
  • 1
Vlad
  • 35,022
  • 6
  • 77
  • 199