数组和长度C ++ [英] Arrays and length in C++

查看:135
本文介绍了数组和长度C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到尽可能一些函数的参数传递的数组的长度。
在code是这样的:

I'm trying to get the length of an array passed as a parameter on some function. The code is look like this :

double getAverage(int numbers[])
{
    int length = sizeof(numbers)/sizeof(numbers[0]);
    // here the result of the length is 1.
    int sum = 0;
    for (int i = 0 ; i < length ; i++)
    {
        sum += numbers[i];
    }
    return (double)sum / length;
}

int main()
{
    int numbers[8] = {1,2,3,4,5,6,7,8};
    //if I call here sizeof(numbers)/sizeof(numbers[0] the result will be 8 as it   
    //should be.
    cout << getAverage(numbers) << endl;
    return 0;
}

我的问题是如何获得,通过引用作为函数的参数传递(虽然我知道每个数组通过引用传递)数组的长度?
我知道有很多关于寻找数组长度在C / C ++,但没有他们中的一个给我,我要找的答案的问题。
先谢谢了。

My question is how to get the array length which is passed as argument of a function by reference(although I know that every array is passed by reference)? I know that there is a lot of questions about finding the array length in C/C++ but no one of them give me the answer which I'm looking for. Thanks in advance.

推荐答案

如果你必须使用一个数组,你可以模板化的功能:

If you must use an array, you could 'templatize' your function:

template <size_t length> double getAverage(int (&numbers)[length]) {
    int sum = 0;
    for (int i = 0 ; i < length ; i++)
    {
        sum += numbers[i];
    }
    return (double)sum / length;
} 

这篇关于数组和长度C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆