-1

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;

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 3
    Array function parameters are C++'s biggest lie. `long long a[]` looks like it declares an array, but it is actually silently transformed into a `long long * a` parameter. And a range based for loop can't work with just a pointer because there is no way to determine how long the range is from just a pointer. You need to either wrap the pointer and size in a span, or use the old fashion for loop. – François Andrieux Sep 09 '22 at 13:10
  • Does this answer your question? https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay – 463035818_is_not_an_ai Sep 09 '22 at 13:10
  • A [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) might help. – Jason Sep 09 '22 at 13:24
  • Maybe look into [`span`](https://stackoverflow.com/q/45723819/1741542), see also https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-range or https://en.cppreference.com/w/cpp/container/span – Olaf Dietsche Sep 09 '22 at 13:34

1 Answers1

0

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!