有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
正如其他人所说,您可以使用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)。
其他回答
#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;
}
而不是使用内置的数组函数aka:
int x[3] = {0, 1, 2};
您应该使用数组类和数组模板。试一试:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。
Name_of_Array.size();
这应该返回数组中元素的长度。
如果你指的是c风格的数组,那么你可以这样做:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
这对指针不起作用(即它对以下任何一个都不起作用):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
在c++中,如果你想要这种行为,那么你应该使用容器类;可能std::向量。
有没有办法找出一个数组有多少个值?
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.