C++中数组的元素计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4839626/
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
Element count of an array in C++
提问by Albus Dumbledore
Let's say I have an array arr
. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])
?
假设我有一个数组arr
。以下什么时候不会给出数组的元素数:sizeof(arr) / sizeof(arr[0])
?
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
我只能处理一种情况:数组包含具有数组类型的不同派生类型的元素。
Am I right and are there (I am almost positive there mustbe) other such cases?
我说的对,并在那里(我几乎可以肯定有一定定)等这样的情况?
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
很抱歉这个微不足道的问题,我是一名 Java 开发人员,我对 C++ 还很陌生。
Thanks!
谢谢!
回答by Nawaz
Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?
假设我有一个数组 arr。以下什么时候不会给出数组的元素数:sizeof(arr) / sizeof(arr[0])?
One thing I've often seen new programmers doing this:
我经常看到新程序员这样做的一件事:
void f(Sample *arr)
{
int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}
Sample arr[10];
f(arr);
So new programmers think the value of count
will be 10. But that's wrong.
所以新程序员认为 的值count
将是 10。但这是错误的。
Even this is wrong:
即使这是错误的:
void g(Sample arr[]) //even more deceptive form!
{
int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10
}
It's all because once you pass an array to any of these functions, it becomes pointertype, and so sizeof(arr)
would give the size of pointer, not array!
这都是因为一旦你将一个数组传递给这些函数中的任何一个,它就会变成指针类型,因此sizeof(arr)
会给出指针的大小,而不是数组!
EDIT:
编辑:
The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:
以下是一种优雅的方式,您可以将数组传递给函数,而不会让它衰减为指针类型:
template<size_t N>
void h(Sample (&arr)[N])
{
size_t count = N; //N is 10, so would be count!
//you can even do this now:
//size_t count = sizeof(arr)/sizeof(arr[0]); it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!
回答by EboMike
Arrays in C++ are very different from those in Java in that they are completely unmanaged. The compiler or run-time have no idea whatsoever what size the array is.
C++ 中的数组与 Java 中的数组非常不同,因为它们是完全不受管理的。编译器或运行时不知道数组的大小。
The information is only known at compile-time if the size is defined in the declaration:
如果在声明中定义了大小,则该信息仅在编译时才知道:
char array[256];
In this case, sizeof(array) gives you the proper size.
在这种情况下, sizeof(array) 为您提供适当的大小。
If you use a pointer as an array however, the "array" will just be a pointer, and sizeof will not give you any information about the actual size of the array.
但是,如果您将指针用作数组,则“数组”将只是一个指针,而 sizeof 不会为您提供有关数组实际大小的任何信息。
STL offers a lot of templates that allow you to have arrays, some of them with size information, some of them with variable sizes, and most of them with good accessors and bounds checking.
STL 提供了许多模板,允许您拥有数组,其中一些具有大小信息,一些具有可变大小,并且大多数具有良好的访问器和边界检查。
回答by GManNickG
There are no cases where, given an array arr
, that the value of sizeof(arr) / sizeof(arr[0])
is not the count of elements, by the definition of array and sizeof
.
根据 array 和 的定义,没有任何情况下,给定一个数组arr
, 的值sizeof(arr) / sizeof(arr[0])
不是元素的数量sizeof
。
In fact, it's even directly mentioned (§5.3.3/2):
事实上,它甚至被直接提到(第 5.3.3/2 节):
.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of nelements is ntimes the size of an element.
.... 应用于数组时,结果是数组中的总字节数。这意味着n 个元素的数组的大小是元素大小的n倍。
Emphasis mine. Divide by the size of an element, sizeof(arr[0])
, to obtain n.
强调我的。除以元素的大小sizeof(arr[0])
,得到n。
回答by par
No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type. In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.
不,仍然会产生正确的值,因为您必须将数组定义为单一类型的所有元素或指向类型的指针。在任何一种情况下,数组大小在编译时都是已知的,因此 sizeof(arr) / sizeof(arr[0]) 始终返回元素计数。
Here is an example of how to use this correctly:
以下是如何正确使用它的示例:
int nonDynamicArray[ 4 ];
#define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )
I'll go one further here to show whento use this properly. You won't use it very often. It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later. It is a construct that is primarily useful for maintenance. The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add morecommands to later. In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:
我将在这里进一步说明何时正确使用它。你不会经常使用它。当您想专门定义一个数组时,它主要有用,以便您可以在以后不更改大量代码的情况下向其中添加元素。它是一种主要用于维护的构造。规范示例(当我无论如何考虑它时;-)正在为您打算稍后添加更多命令的某个程序构建一个命令表。在这个例子中,为了维护/改进你的程序,你需要做的就是向数组中添加另一个命令,然后添加命令处理程序:
char *commands[] = { // <--- note intentional lack of explicit array size
"open",
"close",
"abort",
"crash"
};
#define kCommandsCount ( sizeof(commands) / sizeof(commands[ 0 ]) )
void processCommand( char *command ) {
int i;
for ( i = 0; i < kCommandsCount; ++i ) {
// if command == commands[ i ] do something (be sure to compare full string)
}
}
回答by Bj?rn Pollex
First off, you can circumvent that problem by using std::vector
instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:
首先,您可以通过使用std::vector
而不是数组来规避该问题。其次,如果您将派生类的对象放入超类的数组中,您将经历切片,但好消息是,您的公式将起作用。C++ 中的多态集合是使用指针实现的。这里有三个主要选项:
- normal pointers
- a collection of
boost::shared_ptr
- a Boost.Pointer Container
- 普通指针
- 一个集合
boost::shared_ptr
- 一个Boost.Pointer 容器
回答by Karl Knechtel
Let's say I have an array arr. When would the following not give the number of elements of the array:
sizeof(arr) / sizeof(arr[0])
?
假设我有一个数组 arr。以下什么时候不会给出数组的元素数:
sizeof(arr) / sizeof(arr[0])
?
In contexts where arr
is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.
在arr
实际上不是数组的上下文中(而是指向初始元素的指针)。其他答案解释了这是如何发生的。
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
我只能处理一种情况:数组包含具有数组类型的不同派生类型的元素。
This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).
这不可能发生(从根本上讲,这与 Java 数组不能很好地与泛型配合使用的原因相同)。数组是静态类型的;它保留了为特定类型(基本类型)调整大小的内存“插槽”。
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
很抱歉这个微不足道的问题,我是一名 Java 开发人员,我对 C++ 还很陌生。
C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[]
in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size()
with this class where you would use .length
in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)
C++ 数组不是一流的对象。您可以使用 boost::array 使它们的行为更像 Java 数组,但请记住,您仍将拥有值语义而不是引用语义,就像其他所有内容一样。(特别是,这意味着你不能真正声明一个类似于Foo[]
Java 中的类型的变量,也不能用另一个不同大小的数组替换一个数组;数组大小是类型的一部分。).size()
在你需要的地方使用这个类.length
在 Java 中使用。(它还提供了为 C++ 迭代器提供常用接口的迭代器。)
回答by Mindaugas P.
_countof(my_array) in MSVC
MSVC 中的 _countof(my_array)
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
我只能处理一种情况:数组包含具有数组类型的不同派生类型的元素。
Elements of an array in C++ are objects, not pointers, so you cannot have derived type object as an element.
C++ 中数组的元素是对象,而不是指针,因此不能将派生类型对象作为元素。
And like mentioned above, sizeof(my_array) (like _countof() as well) will work just in the scope of array definition.
就像上面提到的, sizeof(my_array) (也像 _countof() )将只在数组定义的范围内工作。
回答by jamesc1101
Use the Microsoft "_countof(array)" Macro. This link to the Microsoft Developer Network explains it and offers an example that demonstrates the difference between "sizeof(array)" and the "_countof(array)" macro.
使用 Microsoft“_countof(array)”宏。此 Microsoft Developer Network 链接对此进行了解释,并提供了一个示例来演示“sizeof(array)”和“_countof(array)”宏之间的区别。
回答by Matthew McCord
It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof
.
似乎如果您知道数组中元素的类型,您也可以使用sizeof
.
int numList[] = { 0, 1, 2, 3, 4 };
cout << sizeof(numList) / sizeof(int);
// => 5
回答by Wojtek B
I know is old topic but what about simple solution like while loop?
我知道这是一个老话题,但是像 while 循环这样的简单解决方案呢?
int function count(array[]) {
int i = 0;
while(array[i] != NULL) {
i++;
}
return i;
}
I know that is slower than sizeof() but this is another example of array count.
我知道这比 sizeof() 慢,但这是数组计数的另一个例子。