Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在函数中引用自动数组迭代器_C++_Arrays_C++11 - Fatal编程技术网

C++ 在函数中引用自动数组迭代器

C++ 在函数中引用自动数组迭代器,c++,arrays,c++11,C++,Arrays,C++11,这里是一个简单的例子,我在这里找到数组的最大值 我试图在传入函数的数组中使用自动迭代器。 当我在函数体中使用相同的代码时,没有错误 函数max中的引用创建编译错误 cpp:7:14: error: invalid range expression of type 'int *'; no viable 'begin' function available for (auto& x: array){ ^ ~~~~~ 这是我当前的代码,

这里是一个简单的例子,我在这里找到数组的最大值

我试图在传入函数的数组中使用自动迭代器。 当我在函数体中使用相同的代码时,没有错误

函数max中的引用创建编译错误

cpp:7:14: error: invalid range expression of type 'int *'; no viable 'begin' function available
        for (auto& x: array){
                    ^ ~~~~~
这是我当前的代码,我在“normalMax”中包含了对正常用法的引用和一个内联主体函数

我想知道为什么“max”函数中的迭代器会产生错误

#include <iostream>
//max num

//causes an error
int max(int* array){
    int max = 0;
    for (auto& x: array){
        if (x >max)
            max = x;
    }
return max;
};
//normal behavior
int normalMax(int* array){
    int max = 0;
    for (int i=0; i<4; i++){
        if (i >max)
            max = i;
    }
return max;
};

int main(){

    int A[] = {1,2,3,4,5};
    int B[] = {5,6,10,100};
    int max = 0;
    //Works no Error
    for (auto& x: B){
        if (x >max)
            max = x;
    }
    std::cout <<max;
    //100
    normalMax(B);
    //max(B);
    //compile error
    return 0;
}
#包括
//最大数
//引起错误
最大整数(整数*数组){
int max=0;
用于(自动和x:array){
如果(x>最大值)
max=x;
}
返回最大值;
};
//正常行为
int normalMax(int*数组){
int max=0;
对于(int i=0;imax)
max=i;
}
返回最大值;
};
int main(){
int A[]={1,2,3,4,5};
int B[]={5,6,10100};
int max=0;
//没有错误
用于(自动和x:B){
如果(x>最大值)
max=x;
}

std::cout如果要将数组传递给函数,以便编译器可以推断其长度,则需要将其作为引用传递,而不是通过[Decaded]指针:

template <std::size_t N>
int max(int const (&array)[N]) {
    int max = 0;
    for (auto& x: array) {
        if (x >max) {
            max = x;
        }
    }
    return max;
}
模板
int max(int常量和数组)[N]){
int max=0;
用于(自动和x:array){
如果(x>最大值){
max=x;
}
}
返回最大值;
}

作为旁注:函数定义后没有分号。此外,函数也不是特别有用,因为您可能应该返回最大元素的位置,而不仅仅是它的值:位置是隐式确定的,可能包含信息。当然,一旦找到正确的位置,您应该ld还返回正确的最佳值,该值实际上是最大值的最右边版本。

数组实际上是一个指针。与数组不同。ranged for循环不能对指针进行操作,只能对数组和某些类进行操作。是的,
数组
是一个指针,编译器无法判断数组的大小。因此您无法不要使用这样的循环。谢谢,这样做更有意义。解决方案是通过引用传递数组吗?请改用
std::array
。它不会像C数组那样衰减为指针。您也可以使用此
templateint max(array\u t&a);