有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
只是一个想法,但只是决定创建一个计数器变量,并将数组大小存储在位置[0]。我删除了函数中的大部分代码,但你会看到退出循环后,prime[0]被分配为'a'的最终值。我尝试使用矢量,但VS Express 2013不太喜欢。还要注意,'a'从1开始,以避免覆盖[0],并在开始时初始化以避免错误。我不是专家,只是想分享一下。
int prime[] = {0};
int primes(int x, int y){
using namespace std; int a = 1;
for (int i = x; i <= y; i++){prime[a] = i; a++; }
prime[0] = a; return 0;
}
其他回答
下面是谷歌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++ /CX(在Visual Studio中使用c++编写UWP应用程序时),我们可以通过简单地使用size()函数来查找数组中值的数量。
源代码:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
如果你计算size_of_array的输出将是:
>>> 4
您可以使用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;
}
我在这里提供了一个棘手的解决方案:
你总是可以在第一个元素中存储长度:
// malloc/new
arr[0] = length;
arr++;
// do anything.
int len = *(arr-1);
free(--arr);
代价是在调用free时必须—arr
正如其他人所说,您可以使用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)。