C++ 如何找到数组的长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4108313/
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
How do I find the length of an array?
提问by Maxpm
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.
有没有办法找到一个数组有多少个值?检测我是否已经到达数组的末尾也可以。
采纳答案by Oliver Charlesworth
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 (i.e. it won'twork 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; probably std::vector
.
在 C++ 中,如果你想要这种行为,那么你应该使用容器类;大概std::vector
。
回答by Motti
As other's said you can use the sizeof(arr)/sizeof(*arr)
but this will give you the wrong answer for pointer types that aren't arrays.
正如其他人所说,您可以使用 ,sizeof(arr)/sizeof(*arr)
但是对于不是数组的指针类型,这会给您错误的答案。
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
This has the nice property of failing to compile for non array types (visual studio has _countof
which does this). The constexpr
makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).
这有一个很好的特性,即无法为非数组类型编译(visual studio 可以_countof
这样做)。这constexpr
使它成为编译时表达式,因此它对宏没有任何缺点(至少我不知道)。
You can also consider using std::array
from C++11 which exposes its length with no overhead over a native C array.
您还可以考虑使用std::array
来自 C++11 的内容,它公开了它的长度,而不会超过本机 C 数组的开销。
C++17has std::size()
in the <iterator>
header which does the same and works for STL containers too (thanks to @Jon C).
C ++ 17具有std::size()
在<iterator>
其中做同样的和适用于STL容器太(感谢报头@乔恩Ç)。
回答by MahlerFive
Doing sizeof( myArray )
will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof( myArray[0] )
这样做sizeof( myArray )
将使您获得为该数组分配的总字节数。然后,您可以通过除以数组中一个元素的大小来找出数组中的元素数:sizeof( myArray[0] )
回答by Jon C
While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size()
, which returns the number of elements in both a std container or a C-style array. For example:
虽然这是一个老问题,但值得更新 C++17 的答案。在标准库中,现在有模板函数std::size()
,它返回 std 容器或 C 样式数组中的元素数。例如:
#include <iterator>
uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
回答by Prasoon Saurav
Is there a way to find how many values an array has?
有没有办法找到一个数组有多少个值?
Yes!
是的!
Try sizeof(array)/sizeof(array[0])
尝试 sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
检测我是否已经到达数组的末尾也可以。
I dont see any way for this unless your array is an array of characters (i.e string).
除非您的数组是字符数组(即字符串),否则我看不到任何方法。
P.S : In C++ always use std::vector
. There are several inbuilt functions and an extended functionality.
PS:在 C++ 中总是使用std::vector
. 有几个内置功能和扩展功能。
回答by eq-
std::vector
has a method size()
which returns the number of elements in the vector.
std::vector
有一个方法size()
可以返回向量中元素的数量。
(Yes, this is tongue-in-cheek answer)
(是的,这是半开玩笑的回答)
回答by JukkaP
#include <iostream>
int main ()
{
using namespace std;
int arr[] = {2, 7, 1, 111};
auto array_length = end(arr) - begin(arr);
cout << "Length of array: " << array_length << endl;
}
回答by Jaege
Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header <type_traits>
.
从 C++11 开始,引入了一些新模板来帮助减少处理数组长度时的痛苦。所有这些都在 header 中定义<type_traits>
。
If
T
is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.If
T
is an array type, provides the member constant value equal to the number of elements along theN
th dimension of the array, ifN
is in [0,std::rank<T>::value
). For any other type, or ifT
is array of unknown bound along its first dimension andN
is 0, value is 0.If
T
is an array of some typeX
, provides the member typedef type equal toX
, otherwise type isT
. Note that ifT
is a multidimensional array, only the first dimension is removed.std::remove_all_extents<T>::type
If
T
is a multidimensional array of some typeX
, provides the member typedef type equal toX
, otherwise type isT
.
如果
T
是数组类型,则提供等于数组维数的成员常量值。对于任何其他类型,值为 0。如果
T
是数组类型,则提供等于沿N
数组第 th 维的元素数的成员常量值,如果N
在 [0,std::rank<T>::value
) 中。对于任何其他类型,或者如果T
是沿其第一维的未知边界数组并且N
为 0,则值为 0。如果
T
是某种类型的数组X
,则提供成员 typedef type 等于X
,否则 type isT
。请注意,如果T
是多维数组,则仅删除第一维。std::remove_all_extents<T>::type
如果
T
是某种类型的多维数组X
,则提供成员 typedef type 等于X
,否则 type isT
。
To get the length on any dimension of a multidimential array, decltype
could be used to combine with std::extent
. For example:
要获得多维数组的任何维度的长度,decltype
可用于与std::extent
. 例如:
#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent
template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }
template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
// New way
constexpr auto l1 = std::extent<decltype(a)>::value; // 5
constexpr auto l2 = std::extent<decltype(a), 1>::value; // 4
constexpr auto l3 = std::extent<decltype(a), 2>::value; // 3
constexpr auto l4 = std::extent<decltype(a), 3>::value; // 0
// Mixed way
constexpr auto la = length(a);
//constexpr auto lpa = length(*a); // compile error
//auto lpa = length(*a); // get at runtime
std::remove_extent<decltype(a)>::type pa; // get at compile time
//std::remove_reference<decltype(*a)>::type pa; // same as above
constexpr auto lpa = length(pa);
std::cout << la << ' ' << lpa << '\n';
// Old way
constexpr auto la2 = sizeof(a) / sizeof(*a);
constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
std::cout << la2 << ' ' << lpa2 << '\n';
return 0;
}
BTY, to get the total number of elements in a multidimentional array:
BTY,获取多维数组中的元素总数:
constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
Or put it in a function template:
或者把它放在一个函数模板中:
#include <iostream>
#include <type_traits>?
template<class T>
constexpr size_t len(T &a)
{
return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}
int main()
{
int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
constexpr auto ttt = len(a);
int i;
std::cout << ttt << ' ' << len(i) << '\n';?
return 0;
}
More examples of how to use them could be found by following the links.
可以通过以下链接找到有关如何使用它们的更多示例。
回答by metal
There's also the TR1/C++11/C++17 way (see it Live on Coliru):
还有 TR1/C++11/C++17 方式(参见Live on Coliru):
const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n = std::extent< decltype(s) >::value; // From <type_traits>
constexpr auto n2 = std::extent_v< decltype(s) >; // C++17 shorthand
const auto a = std::array{ "1"s, "2"s, "3"s }; // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;
std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
回答by Mr. Foots
Instead of using the built in array function aka:
而不是使用内置数组函数又名:
int x[3] = {0, 1, 2};
you should use the array class and the array template. Try:
您应该使用数组类和数组模板。尝试:
#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
So now if you want to find the length of the array, all you have to do is using the size function in the array class.
所以现在如果你想找到数组的长度,你所要做的就是使用数组类中的 size 函数。
Name_of_Array.size();
and that should return the length of elements in the array.
这应该返回数组中元素的长度。