ERROR: begin was not declared in this scope for(auto x:a)

Viewed 40

pair<long long, long long> getMinMax(long long a[], int n) {
    
    pair<long long,long long> p;
    p.first=a[0];   // min
    p.second=a[0];  //max
    
    for(auto x:a)
    // for(int i=0; i<n;i++)
    {
        // long long x=a[i];
        if(x<p.first)
            p.first=x;
        if(x>p.second)
            p.second=x;
    }
    return p;
}

WROTE THIS CODE

it shows error on for(auto x:a);

what is wrong with that , please explain;

1 Answers

You can use templates to pass an C stylish array by reference like the following:

#include <iostream> // for std::cout
#include <cstddef>  // for std::size_t

template<std::size_t N>
void foo(int (&arr)[N]) {
    for(auto x: arr) { 
      std::cout << x << ' ';
    }
}
int main() {
    int arr[] = {1,2,3};
    foo(arr); // outputs: 1 2 3
}

(N is the array size) Hope that helps!

Related