Reputation: 51
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;
}
Upvotes: 3
Views: 3039
Reputation: 32847
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;
}
Upvotes: 4