有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


当前回答

避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。

在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)

其他回答

下面是谷歌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()函数给出了字节数,所以在其他函数中,它将返回分配给指针的字节数,而不是整个数组。所以这种方法行不通。

但我相信你能根据你的要求找到一个好办法。

快乐的编码。

您可以使用sizeof()操作符,该操作符用于相同的目的。

请参阅下面的示例代码

#include <iostream>
using namespace std;
int main() {
  int arr[] = {10,20,30,40,50,60};
  int arrSize = sizeof(arr)/sizeof(arr[0]);
  cout << "The size of the array is: " << arrSize;
  return 0;
}

vector有一个size()方法,该方法返回vector中元素的数量。

(是的,这是半开玩笑的回答)

对于c++ /CX(在Visual Studio中使用c++编写UWP应用程序时),我们可以通过简单地使用size()函数来查找数组中值的数量。

源代码:

string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);

如果你计算size_of_array的输出将是:

>>> 4