C++ 如何获取数组的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/874169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:43:27  来源:igfitidea点击:

How to get the size of an Array?

c++arrays

提问by Ivan Prodanov

In C# I use the Length property embedded to the array I'd like to get the size of. How to do that in C++?

在 C# 中,我使用嵌入到我想要获取大小的数组的 Length 属性。如何在 C++ 中做到这一点?

回答by Johannes Schaub - litb

It really depends what you mean by "array". Arrays in C++ will have a size (meaning the "raw" byte-size now) that equals to N times the size of one item. By that one can easily get the number of items using the sizeofoperator. But this requires that you still have access to the type of that array. Once you pass it to functions, it will be converted to pointers, and then you are lost. No size can be determined anymore. You will have to construct some other way that relies on the value of the elements to calculate the size.

这真的取决于你所说的“数组”是什么意思。C++ 中的数组的大小(现在意味着“原始”字节大小)等于一项大小的 N 倍。通过该sizeof操作符,可以轻松获取项目数。但这要求您仍然可以访问该数组的类型。一旦你把它传递给函数,它就会被转换成指针,然后你就迷失了。无法再确定大小。您将不得不构建一些依赖于元素值来计算大小的其他方式。

Here are some examples:

这里有些例子:

int a[5];
size_t size = (sizeof a / sizeof a[0]); // size == 5

int *pa = a; 

If we now lose the name "a" (and therefor its type), for example by passing "pa" to a function where that function only then has the value of that pointer, then we are out of luck. We then cannot receive the size anymore. We would need to pass the size along with the pointer to that function.

如果我们现在失去了名称“a”(以及它的类型),例如通过将“pa”传递给一个函数,而该函数只有那个指针的值,那么我们就不走运了。然后我们就不能再收到尺寸了。我们需要将大小与指向该函数的指针一起传递。

The same restrictions apply when we get an array by using new. It returns a pointer pointing to that array's elements, and thus the size will be lost.

当我们使用new. 它返回一个指向该数组元素的指针,因此大小将丢失。

int *p = new int[5];
  // can't get the size of the array p points to. 
delete[] p;

It can't return a pointer that has the type of the array incorporated, because the size of the array created with newcan be calculated at runtime. But types in C++ must be set at compile-time. Thus, newerases that array part, and returns a pointer to the elements instead. Note that you don't need to mess with newin C++. You can use the std::vectortemplate, as recommended by another answer.

它不能返回一个包含数组类型的指针,因为创建的数组的大小new可以在运行时计算。但是 C++ 中的类型必须在编译时设置。因此,new擦除该数组部分,并返回指向元素的指针。请注意,您不需要new在 C++ 中搞砸。您可以std::vector按照另一个答案的建议使用模板。

回答by Noldorin

Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size.

C/C++ 中的数组不将它们的长度存储在内存中,因此不可能仅仅通过一个指向数组的指针来找到它们的大小。在这些语言中使用数组的任何代码都依赖于一个常数已知大小,或者一个单独的变量被传递来指定它们的大小。

A common solution to this, if it does present a problem, is to use the std::vectorclass from the standard library, which is much closer to a managed (C#) array, i.e. stores its length and additionally has a few useful member functions (for searching and manipulation).

如果确实存在问题,对此的常见解决方案是使用std::vector标准库中的类,该类更接近托管 (C#) 数组,即存储其长度并另外具有一些有用的成员函数(用于搜索和操纵)。

Using std::vector, you can simply call vector.size()to get its size/length.

使用std::vector,您可以简单地调用vector.size()以获取其大小/长度。

回答by Pete Kirkham

To count the number of elements in a static array, you can create a template function:

要计算静态数组中的元素数量,您可以创建一个模板函数:

template < typename T, size_t N >
size_t countof( T const (&array)[ N ] )
{
    return N;
} 

For standard containers such as std::vector, the size()functionis used. This pattern is also used with boost arrays, which are fixed size arrays and claim no worse performance to static arrays. The code you have in a comment above should be:

对于标准容器,例如std::vector,使用该size()函数。这种模式也与boost 数组一起使用,它是固定大小的数组,并且声称没有比静态数组更差的性能。您在上面评论中的代码应该是:

for ( std::vector::size_type i(0); i < entries.size(); ++i )

( assuming the size changes in the loop, otherwise hoist it, ) rather than treating size as a member variable.

(假设循环中的大小发生变化,否则将其提升,)而不是将大小视为成员变量。

回答by Gavin H

In C/C++, arrays are simply pointers to the first element in the array, so there is no way to keep track of the size or # of elements. You will have to pass an integer indicating the size of the array if you need to use it.

在 C/C++ 中,数组只是指向数组中第一个元素的指针,因此无法跟踪元素的大小或数量。如果您需要使用它,您将必须传递一个指示数组大小的整数。

Strings mayhave their length determined, assuming they are null terminated, by using the strlen() function, but that simply counts until the \0 character.

字符串可以通过使用 strlen() 函数来确定它们的长度,假设它们是空终止的,但这只是计数到 \0 字符。

回答by Timo Geusch

Als Nolrodin pointed out above, it is pretty much impossible to get the size of an plain array in C++ if you only have a pointer to its first element. However if you have a fixed-size array there is a well-known C trick to work out the number of elements in the array at compile time, namely by doing:

Als Nolrodin 上面指出,如果你只有一个指向它的第一个元素的指针,那么在 C++ 中获得普通数组的大小几乎是不可能的。但是,如果您有一个固定大小的数组,则有一个众所周知的 C 技巧可以在编译时计算数组中的元素数量,即通过执行以下操作:

GrmblFx loadsOfElements[1027];
GrmblFx_length = sizeof(loadsOfElements)/sizeof(GrmblFx);