有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


当前回答

答:

int number_of_elements = sizeof(array)/sizeof(array[0])

解释:

由于编译器为每种类型的数据设置了特定大小的内存块,而数组只是这些数据的一组,因此只需将数组的大小除以数据类型的大小。如果我有一个包含30个字符串的数组,我的系统会为数组的每个元素(字符串)留出24个字节。在30个元素时,总共是720个字节。720/24 == 30个元素。这个小而紧凑的算法是:

Int number_of_elements = sizeof(array)/sizeof(array[0]),这相当于

Number_of_elements = 720/24

请注意,您不需要知道数组是什么数据类型,即使它是自定义数据类型。

其他回答

我认为这是可行的:

for(int i=0;array[i];i++)
{
 //do_something
}  

给你:

#include <iostream>
using namespace std;

int main() {
 int arr[] = {10,20,30,40,50,60};
 int arrSize = sizeof(arr)/sizeof(arr[0]);
 cout << "The size of the array is: " << arrSize;
return 0;
}

还有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

而不是使用内置的数组函数aka:

 int x[3] = {0, 1, 2};

您应该使用数组类和数组模板。试一试:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。

Name_of_Array.size();

这应该返回数组中元素的长度。

虽然这是一个老问题,但值得将答案更新到c++ 17。在标准库中,现在有一个模板化函数std::size(),它返回std容器或c风格数组中的元素数量。例如:

#include <iterator>

uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4