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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…