1. 算术表达式: #include <iostream>int main() { int arr[4]; std::cout << sizeof( arr ) / sizeof( arr[0] ) << std::endl; // 输出4}或#include <iostream>int main() { int arr[4]; std::cout << sizeof( arr ) / sizeof( *arr ) << std::endl; // 输出4}//测试通过 2. 函数模板参数自动推断: #include <iostream> template <typename T, size_t N>inline size_t Count( T ( & arr )[N] ) { return N;} int main() { int arr[4]; std::cout << Count( arr ) << std::endl; // 输出4}//测试通过 3. 标准C++模板库: #include <type_traits> // 注意包含此头文件.#include <iostream> int main() { int arr[4]; std::cout << std::extent<decltype( arr ), 0>::value << std::endl; // 输出4}//测试未通过 4. 模板特化与自动类型推断: include <iostream>template <typename T>class ComputeSize; template <typename T, size_t N>class ComputeSize<T[N]> {public: static const size_t value = N;}; int main() { int arr[4]; std::cout << ComputeSize<decltype( arr )>::value << std::endl; // 输出4}//测试未通过 5. Visual C++编译器预定义宏: #include <cstdlib>#include <iostream> int main() { int arr[4]; std::cout << _countof( arr ) << std::endl; // 输出4.}//测试通过 6. boost库: #include "boost/range.hpp"#include <iostream> int main(){ int arr[4]; std::cout << boost::size( arr ) << std::endl; // 输出4}//测试未通过
上面的方法适用于静态数组,动态的数组(new[])是无法获取元素个数的。
#include“string.h”
strlen(a)求字符数组的大小是
sizeof(a)/sizeof(a[0]);这种基本上万能