'why i am facing this error: request for member 'size' in 'arr', which is of non-class type 'int [n]' for(int j=arr.size()-1; j>=0; j--){
I am facing an error:
request for member size in arr which is of non class type
I could not figure out what is happening.
#include <iostream>
#include <vector>
using namespace std;
// reversing an array;`
int main(){
int n, a;
std::vector<int> vect;
cout << "enter size: ";
cin >> n;
int arr[n];
cout << "enter numbers in array ---> " << endl;
for(int i=0; i<n; i++){
cin >> arr[i];
}
//logic to reverse
for(int j=arr.size()-1; j>=0; j--){
a = arr[j];
vect.push_back(a);
}
for(int k=0; k<n; k++){
cout << vect[k];
}
}
Solution 1:[1]
I don't think array type has the function size you can probably use vector instead of arr( vector arr(n,0) )
Solution 2:[2]
The built in array does not have a .size() member function. If you wanted that you would need to use the array in the array header file. But instead you could use for(int j=n-1; j>=0; j--){.
This is your solution:
#include<iostream>
#include <vector>
using namespace std;
// reversing an array;`
int main(){
int n, a;
std::vector<int> vect;
cout << "enter size: ";
cin >> n;
int arr[n];
cout << "enter numbers in array ---> " << endl;
for(int i=0; i<n; i++){
cin >> arr[i];
}
//logic to reverse
for(int j=n-1; j>=0; j--){
a = arr[j];
vect.push_back(a);
}
for(int k=0; k<n; k++){
cout << vect[k];
}
}
Solution 3:[3]
For starters, variable length arrays are not a standard C++ feature. And a variable length array is declared in your code:
cout << "enter size: ";
cin >> n;
int arr[n];
Secondly, arrays are not classes. They do not have member functions. So the expression arr.size() is incorrect.
If the compiler supports the function std::size() declared in the header <iterator> for variable length arrays, you could use the expression std::size(arr) instead of arr.size().
Though, instead of the for loop, you could just write:
#include <iterator>
//...
vect.assign( std::rbegin( arr ), std::rend( arr ) );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | randy_butternubs |
| Solution 2 | |
| Solution 3 | Remy Lebeau |
