3

I tried many things but still, it's giving an error:

no matching function for call to ‘begin(int [n])’

What's the best approach?

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() 
{
    int n;
    cin >> n;
    int arr[n];
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }
    reverse(begin(arr), end(arr));
    for(int j = 0; j < n; j++){
        cout << arr[j] <<" ";
    }
    return 0;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
nidhisoni
  • 51
  • 1
  • 6
  • 6
    change `int arr[n];` to `std::vector arr(n);`. VLA's (`int arr[n]`) are not standard in C++. – NathanOliver Aug 01 '18 at 16:27
  • 4
    "`cin >> n; int arr[n] ;`" - variable length arrays are *not* supported by standard C++. Use `std::vector`. – Jesper Juhl Aug 01 '18 at 16:28
  • Are you compiling your code as modern C++ (C++11/C++14/C++17)? Otherwise that `begin(arr)` has *no* chance of working. – Jesper Juhl Aug 01 '18 at 16:30
  • 2
    And once you've changed to a `std::vector`, and if all you want to do is to print the input in reverse, then use the vectors reverse iterators `rbegin` and `rend` instead. – Some programmer dude Aug 01 '18 at 16:30
  • 1
    "`using namespace std;`" - bad habit. – Jesper Juhl Aug 01 '18 at 16:36
  • 1
    Stuff like `int arr[n]` isn't valid C++, because [C++ doesn't have variable length arrays](https://stackoverflow.com/q/1887097/9254539). Your code only compiles because of a GCC non-standard extension. You should use an `std::vector` instead to make your code portable and avoid blowing out the stack. – eesiraed Aug 01 '18 at 16:59

1 Answers1

3

error:no matching function for call to ‘begin(int [n])’

This is because of that you have used non-standard Variable Length Array, here:

cin >> n;
int arr[n] ;

Therefore, it's not possible to apply the standard algorithms like std::reverse to this kind of non-standard arrays.

if you change it normal array with a size, like:

const int n = 3;
int arr[n] ;

The code what you wrote is valid and will work. See here

However, now you can not input the size of the array.


Whats the best approach?

Use std::vector instead.

Now you also have the option for reverse printing without using std::reverse, but using std::vector::reverse_iterator.(If that's all you wanted)

For instance: See output here

#include <vector>
#include <iostream>
#include <algorithm>

int main() 
{
   int n;
   std::cin >> n;
   std::vector<int> arr(n);
   for(int& ele: arr) std::cin >> ele;
   //std::reverse(std::begin(arr), std::end(arr));
   //for(const int ele: arr) std::cout << ele << " ";
   //or simply
   std::for_each(arr.rbegin(), arr.rend(),[](const int ele){ std::cout << ele << " "; });
   return 0;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88