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

标签 c++ arrays c++11

这是一个简单的例子,我正在寻找数组的最大值。

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

函数 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;
}

最佳答案

如果您想将数组传递给函数以便编译器可以推断出它的长度,您需要将其作为引用传递,而不是通过 [decayed] 指针传递:

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;
}

附带说明:函数定义后没有分号。此外,该函数并不是特别有用,因为您可能更愿意返回最大元素的位置,而不仅仅是它的值:该位置无论如何都是隐式确定的,并且可能携带信息。当然,一旦找到正确的位置,您还应该返回适​​当的最佳值,这实际上是最大值的最右边版本。

关于c++ - 在函数中引用自动数组迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442337/

相关文章:

Java 通过 System.arraycopy() 复制数组 3d

c++ - 如何加快从流到内存的读取行?

c++ - 模板转换函数到 const-reference

c++ - 在 C++ 中使用不同的 IEEE 浮点舍入模式

java - 为什么即使对于不相等的字符串,equalsignorecase 也会返回 true

C++类中的C++过期机制

C++用变量而不是常量表达式初始化数组

c++ - BASS 2.4.4制作时出错

c++ - Win32_NetworkAdapter 类为 boolean NetEnabled 返回 NULL;

c - 结构数组奇怪的输出?