Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Auto Array Iterator in function

Tags:

c++

arrays

c++11

Here is a simple case where I'm finding the Max of an Array.

Im attempting to use an auto iterator in a array passed into my function. When I utilize the same code in my function body no error.

The reference inside the function max creates a compile error

cpp:7:14: error: invalid range expression of type 'int *'; no viable 'begin' function available
        for (auto& x: array){
                    ^ ~~~~~

Here is my current code, i included a reference to normal usage in "normalMax" and a inline main body function.

I want to know why the iterator in the 'max' function produces an error

#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;
}
like image 859
FirstTimer Avatar asked Feb 14 '23 12:02

FirstTimer


1 Answers

If you want to pass an array to a function so you the compiler can deduce its length, you'll need to pass it as reference not via a [decayed] pointer:

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

As a side note: there is no semicolon after the definition of a function. Also, the function isn't particular useful as you should probably rather return the position of the maximum element rather than just its value: the position is determined implicitly anyway and may carry information. Of course, once you locate the correct position you should also return the proper best value which is actually the rightmost version of the maximum.

like image 196
Dietmar Kühl Avatar answered Feb 16 '23 01:02

Dietmar Kühl