有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。
当前回答
#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;
}
其他回答
避免将类型与sizeof一起使用,因为如果改变数组类型,sizeof(array)/sizeof(char)会突然被破坏。
在visual studio中,你有等效的if sizeof(array)/sizeof(*array)。 你可以输入_countof(array)
你可以通过以下方法找到数组的长度:
int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
cout << "Number of elements in arr[] is "<< size;
return 0;
Sizeof (array_name)给出整个数组的大小,Sizeof (int)给出每个数组元素的数据类型的大小。
所以用整个数组的大小除以数组中单个元素的大小就得到了数组的长度。
int array_name[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(array_name)/sizeof(int);
还有TR1/ c++ 11/ c++ 17方式(参见Coliru Live):
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
有没有办法找出一个数组有多少个值?
Yes!
尝试sizeof(数组)/ sizeof(阵列[0])
检测是否已经到达数组的末尾也可以工作。
我看不到任何方法,除非你的数组是一个字符数组(即字符串)。
注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。