数组¶
参考:Arrays (C++)
数组是相似对象的集合
声明¶
数组声明语法有以下四种方式:
decl-specifier identifier [ constant-expression ]
decl-specifier identifier []
decl-specifier identifer [][ constant-expression ] ...
decl-specifier identifier [ constant-expression ] [ constant-expression ] ...
- 声明说明符
- 可选的存储类说明符
- 可选的
cv
限定符 - 数组元素的类名
- 声明符
- 标识符
- 括在方括号内的整型常量表达式。如果使用附加括号声明多个维度,则在第一组括号上可以省略常量表达式
- 包含常量表达式的可选附加括号
- 可选的初始化器
数组中的元素数量由常量表达式给出。数组中的第一个元素是第0
个元素,最后一个元素是(n-1
)元素,其中n是数组可以包含的元素数。常量表达式必须是整型,并且必须大于0
多维数组声明¶
多维数组是通过按顺序放置多个带括号的常量表达式来指定的。在具有初始值列表的多维数组声明中,可以省略指定第一个维度边界的常量表达式
const int cMarkets = 4;
// Declare a float that represents the transportation costs.
double TransportCosts[][cMarkets] = {
{32.19, 47.29, 31.99, 19.11},
{11.29, 22.49, 33.47, 17.29},
{41.97, 22.09, 9.76, 22.55}
};
初始化¶
类数组初始化¶
如果类有构造函数,则该类的数组由构造函数初始化。如果初始值列表中的项少于数组中的元素,则对其余元素使用默认构造函数。如果没有为类定义默认构造函数,则初始值设定项列表必须完整 - 即数组中的每个元素都必须有一个初始值设定项
// initializing_arrays1.cpp
class Point {
public:
Point() {} // Default constructor.
Point(int, int) {} // Construct from two ints
};
// An array of Point objects can be declared as follows:
Point aPoint[3] = {
Point(3, 3) // Use int, int constructor.
};
数组aPoint
的第一个元素使用构造器Point(int, int)
,后续的元素使用默认构造器
静态成员数组初始化¶
静态成员数组(无论是否const
)都可以在其定义中初始化(在类声明之外)
class WindowColors {
public:
static const char *rgszWindowPartList[7];
};
const char *WindowColors::rgszWindowPartList[7] = {
"Active Title Bar", "Inactive Title Bar", "Title Bar Text",
"Menu Bar", "Menu Bar Text", "Window Background", "Frame"};
int main() {
WindowColors colors[3];
for (int i = 0; i < 7; i++) {
cout << colors[0].rgszWindowPartList[i] << endl;
}
}
取值操作¶
参考:
Interpretation of Subscript Operator
有两种方式获取数组指定位置的值
- 使用下标运算符
- 使用间接取值运算符
const int Max1 = 3;
const int Max2 = 4;
int a[Max1][Max2];
for (int i = 0; i < Max1; i++) {
for (int j = 0; j < Max2; j++) {
a[i][j] = i + j;
}
}
// 创建指针数组指向a
int (*b)[Max2] = a;
// 打印第一行元素值
for (int i = 0; i < Max2; i++) {
cout << *(*(b + 0) + i) << endl;
}
// 取第2行第1列的元素值和地址
cout << *(*(b + 2) + 1) << endl;
cout << (*(b + 2) + 1) << endl;
cout << b[2][1] << endl;
cout << &b[2][1] << endl;
结果:
0
1
2
3
3
0x7ffff9bfae54
3
0x7ffff9bfae54
内存排列顺序¶
C++
数组按行进行顺序存储,表示最后一个下标变化最快