0

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];
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

3 Answers3

0

I don't think array type has the function size you can probably use vector instead of arr( vector arr(n,0) )

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 13 '22 at 17:16
0

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];
        }
    }
0

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 ) );
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335