简体   繁体   English

如何获取传递给 function 的数组的长度?

[英]How can I get the length of an array that was passed to a function?

Given the following function:给定以下 function:

template<class T>
void foo(T* ar)
{
    std::cout << sizeof(ar) / sizeof(ar[0]) << std::endl;
    for (int i = 0; i < 6; i++)
        std::cout << ar[i] << " ";
}

And following array:和以下数组:

int ar[] = { 5, 1, 6, 8, 9, 3 };
foo(ar);

I expected the program to print '6' and then the contents of the array.我希望程序先打印“6”,然后再打印数组的内容。 But for some reason, sizeof(ar) / sizeof(ar[0]) evaluates to 1 (since both sizeof(ar) and sizeof(ar[0]) evaluate to '4'), but the print works fine (meaning passed array does contain all 6 elements).但由于某种原因, sizeof(ar) / sizeof(ar[0])评估为 1(因为sizeof(ar)sizeof(ar[0])评估为 '4'),但打印工作正常(意思是通过数组确实包含所有 6 个元素)。

This only happens to arrays passed to functions (I tried evaluating length in main(), where array was declared and it worked fine).这只发生在 arrays 传递给函数(我尝试在 main() 中评估长度,其中声明了数组并且工作正常)。 How can I get the length of an array inside a function?如何获取 function 中的数组长度?

Just declare the parameter as having a referenced type.只需将参数声明为具有引用类型即可。

For example例如

template<class T>
void foo( const T &ar )
{
    size_t n = sizeof(ar) / sizeof(ar[0]);
    std::cout << n << std::endl;
    for (int i = 0; i < n; i++)
        std::cout << ar[i] << " ";
}

Or you may use the following declaration或者您可以使用以下声明

template<class T, size_t N>
void foo( const T ( &ar )[N] )
{
    std::cout << N << std::endl;
    for (int i = 0; i < N; i++)
        std::cout << ar[i] << " ";
}

Otherwise the function deals with a pointer.否则 function 处理指针。 In this case you need specify a second parameter that denotes the length of the array like在这种情况下,您需要指定第二个参数来表示数组的长度,例如

template<class T>
void foo( const T* ar, size_t n )
{
    std::cout << n << std::endl;
    for (int i = 0; i < n; i++)
        std::cout << ar[i] << " ";
}

As the passed array is not being changed in the function then the corresponding parameter should have the qualifier const .由于在 function 中未更改传递的数组,因此相应的参数应具有限定符const

Pay attention to that in the C++ 17 Standard there is introduced standard function std::size declared in the header <iterator> that can be used instead of the expression sizeof(ar) / sizeof(ar[0])注意在 C++ 17 标准中引入了标准 function std::size<iterator>中声明的标准::size 可以用来代替sizeof(ar) / sizeof(ar[0])

So you could write for example in the first shown function所以你可以写例如在第一个显示的 function

size_t n = std::size(ar)`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM