Appearance
L4_02 二维数组/多维数组
一、C++ 二维数组的定义与使用
1.1 定义方式
cpp
#include <iostream>
using namespace std;
int main() {
// 方法1:指定行数和列数
int arr1[3][4];
// 方法2:初始化时指定元素
int arr2[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// 方法3:省略内层大括号
int arr3[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
return 0;
}1.2 访问元素
cpp
int arr[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
// 访问第2行第3列的元素(索引从0开始)
cout << arr[1][2] << endl; // 输出71.3 遍历二维数组
cpp
int arr[3][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}二、C++ 多维数组
2.1 三维数组
cpp
int arr[2][3][4]; // 2个3x4的二维数组
// 初始化
int arr[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};2.2 访问三维数组元素
cpp
cout << arr[1][2][3] << endl; // 输出24三、Python 复合类型的嵌套使用
3.1 列表的嵌套
python
# 创建二维列表
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问元素
print(matrix[0][0]) # 1
print(matrix[1][2]) # 6
# 遍历二维列表
for row in matrix:
for element in row:
print(element, end=" ")
print()3.2 列表推导式创建矩阵
python
# 创建3x3的单位矩阵
identity = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
print(identity)
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]3.3 字典的嵌套
python
students = {
"Alice": {
"age": 20,
"grades": {"math": 95, "english": 88}
},
"Bob": {
"age": 19,
"grades": {"math": 87, "english": 92}
}
}
# 访问嵌套字典
print(students["Alice"]["grades"]["math"]) # 953.4 列表中包含字典
python
books = [
{"title": "Python", "author": "Guido"},
{"title": "C++", "author": "Stroustrup"}
]
for book in books:
print(f"{book['title']} by {book['author']}")四、二维数组的应用
4.1 矩阵加法
cpp
#include <iostream>
using namespace std;
int main() {
int A[2][3] = {{1,2,3}, {4,5,6}};
int B[2][3] = {{7,8,9}, {10,11,12}};
int C[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// 输出结果
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}4.2 矩阵转置
python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 转置矩阵
transposed = [[row[i] for row in matrix] for i in range(3)]
for row in transposed:
print(row)五、示例程序
5.1 C++ 二维数组操作
cpp
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
// 计算对角线元素之和
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += matrix[i][i];
}
cout << "对角线元素之和: " << sum << endl;
// 打印矩阵
cout << "矩阵内容:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}5.2 Python 嵌套数据结构
python
# 学生成绩管理
students = [
{"name": "Alice", "scores": [90, 85, 95]},
{"name": "Bob", "scores": [80, 75, 85]},
{"name": "Charlie", "scores": [95, 90, 88]}
]
# 计算每个学生的平均分
for student in students:
avg = sum(student["scores"]) / len(student["scores"])
print(f"{student['name']}: {avg:.2f}")