Array Size Member Function Compile Error

2019-02-27 22:29发布

问题:

Working with this code:

int myArray[10];
    for(int i = 0; i < myArray.size(); i++)
        cout << myArray[i] << endl;

Compiler error:

error: request for member 'size' in 'myArray', which is of non-class type 'int [10]'|

I must be missing something obvious but I don't see it.

回答1:

Array types are not class types and don't have member functions. So an array doesn't have a member function called size. However, since arrays have compile-time fixed sizes, you know the size is 10:

for(int i = 0; i < 10; i++)
    cout << myArray[i] << endl;

Of course, it's best to avoid magic numbers and put the size in a named constant somewhere. Alternatively, there is a standard library function for determining the length of an array type object:

for(int i = 0; i < std::extent(myArray); i++)
    cout << myArray[i] << endl;

You may, however, use std::array instead, which encapsulates an array type object for you and does provide a size member function:

std::array<int, 10> myArray;
for(int i = 0; i < myArray.size(); i++)
    cout << myArray[i] << endl;


回答2:

You want the sizeof operator:

int myArray[10];
    for(int i = 0; i < (sizeof(myArray)/sizeof(myArray[0])); i++)
        cout << myArray[i] << endl;


回答3:

Size is not defined for static arrays in C++. If you have to use a static array you need to keep track of length of the array in another variables.

Like:

const int size = 10;
int arr[size];
for(int i = 0; i < size; i++){
    cout << myArray[i] << endl;
}

On the other hand, if it's not a requirement to use static arrays, I would recommend you use std::vector instead.

std::vector<int> arr;
for (int i = 0, max = arr.size(); i<max;i++){
  [...]
}