有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
下面是谷歌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.
其他回答
这是一个非常古老和传奇的问题,已经有很多惊人的答案。但是随着时间的推移,新的功能被添加到语言中,所以我们需要根据可用的新功能不断更新。
我只是注意到还没有人提到c++ 20。所以想写答案。
C + + 20
在c++ 20中,标准库中增加了一种新的更好的方法来查找数组的长度,即std:ssize()。这个函数返回一个带符号的值。
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
std::cout << std::ssize(arr);
return 0;
}
C++17
在c++ 17中,(当时)有一个更好的方法来实现same,即在iterator中定义std::size()。
#include <iostream>
#include <iterator> // required for std::size
int main(){
int arr[] = {1, 2, 3};
std::cout << "Size is " << std::size(arr);
return 0;
}
附注:这个方法也适用于矢量。
Old
这种传统的方法已经在许多其他的答案中提到过。
#include <iostream>
int main() {
int array[] = { 1, 2, 3 };
std::cout << sizeof(array) / sizeof(array[0]);
return 0;
}
仅供参考,如果你想知道为什么这种方法不工作时,数组传递给另一个函数。原因是,
在c++中,数组不是按值传递的,而是传递指向数组的指针。在某些情况下,传递整个数组可能是昂贵的操作。你可以通过将数组传递给某个函数来测试这一点,并对那里的数组进行一些更改,然后再次在main中打印数组。你会得到更新的结果。
正如你已经知道的,sizeof()函数给出了字节数,所以在其他函数中,它将返回分配给指针的字节数,而不是整个数组。所以这种方法行不通。
但我相信你能根据你的要求找到一个好办法。
快乐的编码。
对于旧的g++编译器,您可以这样做
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
有没有办法找出一个数组有多少个值?
Yes!
尝试sizeof(数组)/ sizeof(阵列[0])
检测是否已经到达数组的末尾也可以工作。
我看不到任何方法,除非你的数组是一个字符数组(即字符串)。
注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。
我认为这是可行的:
for(int i=0;array[i];i++)
{
//do_something
}
避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。
在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)