有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
执行sizeof myArray将得到分配给该数组的总字节数。然后,您可以通过除以数组中一个元素的大小来找出数组中的元素数量:sizeof myArray[0]
所以,你会得到这样的东西:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
由于sizeof产生size_t,结果LengthOfArray也将是这种类型。
其他回答
执行sizeof myArray将得到分配给该数组的总字节数。然后,您可以通过除以数组中一个元素的大小来找出数组中的元素数量:sizeof myArray[0]
所以,你会得到这样的东西:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
由于sizeof产生size_t,结果LengthOfArray也将是这种类型。
有没有办法找出一个数组有多少个值?
Yes!
尝试sizeof(数组)/ sizeof(阵列[0])
检测是否已经到达数组的末尾也可以工作。
我看不到任何方法,除非你的数组是一个字符数组(即字符串)。
注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。
下面是谷歌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.
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
对于c++ /CX(在Visual Studio中使用c++编写UWP应用程序时),我们可以通过简单地使用size()函数来查找数组中值的数量。
源代码:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
如果你计算size_of_array的输出将是:
>>> 4