Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...