有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
答:
int number_of_elements = sizeof(array)/sizeof(array[0])
解释:
由于编译器为每种类型的数据设置了特定大小的内存块,而数组只是这些数据的一组,因此只需将数组的大小除以数据类型的大小。如果我有一个包含30个字符串的数组,我的系统会为数组的每个元素(字符串)留出24个字节。在30个元素时,总共是720个字节。720/24 == 30个元素。这个小而紧凑的算法是:
Int number_of_elements = sizeof(array)/sizeof(array[0]),这相当于
Number_of_elements = 720/24
请注意,您不需要知道数组是什么数据类型,即使它是自定义数据类型。
其他回答
正如其他人所说,您可以使用sizeof(arr)/sizeof(*arr),但这将为非数组的指针类型提供错误的答案。
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
这具有对非数组类型编译失败的良好属性(Visual Studio有_countof可以做到这一点)。constexpr使它成为编译时表达式,因此它没有任何宏的缺点(至少我不知道)。
你也可以考虑使用c++ 11中的std::array,它公开了它的长度,而不增加C原生数组的开销。
c++ 17在<iterator>头文件中有std::size(),它具有相同的功能,也适用于STL容器(感谢@Jon C)。
使用泛型的一个好的解决方案:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
然后简单地调用arraysize(_Array);来获取数组的长度。
源
vector有一个size()方法,该方法返回vector中元素的数量。
(是的,这是半开玩笑的回答)
答:
int number_of_elements = sizeof(array)/sizeof(array[0])
解释:
由于编译器为每种类型的数据设置了特定大小的内存块,而数组只是这些数据的一组,因此只需将数组的大小除以数据类型的大小。如果我有一个包含30个字符串的数组,我的系统会为数组的每个元素(字符串)留出24个字节。在30个元素时,总共是720个字节。720/24 == 30个元素。这个小而紧凑的算法是:
Int number_of_elements = sizeof(array)/sizeof(array[0]),这相当于
Number_of_elements = 720/24
请注意,您不需要知道数组是什么数据类型,即使它是自定义数据类型。
下面是谷歌Protobuf中ArraySize的一个实现。
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling. Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t. This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.