Home > Blockchain >  why i am facing this error: request for member 'size' in 'arr', which is of non-
why i am facing this error: request for member 'size' in 'arr', which is of non-

Time:03-14

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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 ) );
  • Related