Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c++ - 如何找到数组的长度?(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.

(检测我是否已经到达数组末尾也可以。)

  ask by Maxpm translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you mean a C-style array, then you can do something like:

(如果您的意思是C样式的数组,则可以执行以下操作:)

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;

This doesn't work on pointers (ie 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;

or:

(要么:)

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

In C++, if you want this kind of behavior, then you should be using a container class;

(在C ++中,如果您想要这种行为,则应该使用容器类。)

probably std::vector .

(可能是std::vector 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...