问题
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.
回答1:
I eventually found the answer myself - boost::size()
:
#include <boost/range.hpp>
int array[10];
boost::size(array); // returns 10
回答2:
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...
回答3:
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
回答4:
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);
回答5:
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?
来源:https://stackoverflow.com/questions/8257858/array-size-metafunction-is-it-in-boost-somewhere