如何找到数组的长度? [英] How do I find the length of an array?
本文介绍了如何找到数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法找到一个数组有多少个值?检测我是否已经到达数组的末尾也可以.
Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.
推荐答案
如果你的意思是一个 C 风格的数组,那么你可以这样做:
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
这不适用于指针(即它不适用于以下任一情况):
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
或:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
在 C++ 中,如果你想要这种行为,那么你应该使用容器类;可能是 std::vector
.
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector
.
这篇关于如何找到数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文