二维数组
数组里面还是, 类似数学中的矩阵
#include <iostream>
using namespace std;
int main(){
// int arr[] = {1, 2, 3}
// 定义一个二位数组
const int M = 3, N =4 ;
int arr[M][N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// 遍历
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
cout<<arr[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
}
二维数组的定义方式
1. 数据类型 数组名[行数][列数];
2. 数据类型 数组名[行数][列数] = {{数据1, 数据2...}, ..... {数据n, 数据n+1}....};
3. 数据类型 数组名[行数][列数] = {数据1, 数据2, ......};
4. 数据类型 数组名[][列数] = {数据1, 数据2, ......};
可以省略行, 不可以省略列
#include <iostream>
using namespace std;
int main() {
// 1. 数据类型 数组名[行数][列数];
int arr[2][3];
// 没有赋值时, 数组中的变量是不确定的
for (int i = 0; i < 2 ; ++i) {
for (int j = 0; j < 3; ++j) {
cout<<arr[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
// 赋值
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
cout<<"===================================="<<endl;
for (int i = 0; i < 2 ; ++i) {
for (int j = 0; j < 3; ++j) {
cout<<arr[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
// 2. 数据类型 数组名[行数][列数] = {{数据1, 数据2...}, ..... {数据n, 数据n+1}....};
cout<<"===================================="<<endl;
int arr2[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2 ; ++i) {
for (int j = 0; j < 3; ++j) {
cout<<arr2[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
// 3. 数据类型 数组名[行数][列数] = {数据1, 数据2, ......};
cout<<"===================================="<<endl;
int arr3[2][3] = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < 2 ; ++i) {
for (int j = 0; j < 3; ++j) {
cout<<arr3[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
// 4. 数据类型 数组名[][列数] = {数据1, 数据2, ......};
cout<<"===================================="<<endl;
int arr4[][3] = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < 2 ; ++i) {
for (int j = 0; j < 3; ++j) {
cout<<arr4[i][j]<<"\t"; //第 i 行 第 j 列
}
cout<<endl;
}
}
⼆维数组数组名
- 查看⼆维数组所占内存空间
- 获取⼆维数组⾸地址
image
#include <iostream>
using namespace std;
int main() {
// 计算三名同学的总成绩
int scores[][3] = {{100, 100, 100}, {90, 30, 100}, {60, 70, 80}};
string names[] = {"zhangsan", "lisi", "wangwu"};
for (int i = 0; i < 3; ++i) {
int sum = 0;
for (int j = 0; j < 3; ++j) {
sum += scores[i][j];
}
cout<<names[i] <<" total score = "<<sum<<endl; //
cout<<names[i] <<" mean score = "<<sum/3.0<<endl; //
}
}
编写程序实现矩阵的转置操作(行变列, 列变行)
#include <iostream>
using namespace std;
int main() {
int X[5][4]={{1, 2, 3, 4}, { 5, 6, 7, 8,}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}};
int XT[4][5];
cout<< "T before ------------------------------" <<endl;
for (int i = 0; i < 5 ; ++i) {
for (int j = 0; j < 4; ++j) {
cout<<X[i][j]<<"\t";
}
cout<<endl;
}
// 转置
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 4; ++j) {
// 核心代码 行变列 , 列变行
XT[j][i] = X[i][j];
}
}
cout<< "T After ------------------------------" <<endl;
for (int i = 0; i < 4 ; ++i) {
for (int j = 0; j < 5; ++j) {
cout<<XT[i][j]<<"\t";
}
cout<<endl;
}
}
作业
统计数组a和b对应位置元素相等的个数
int a[3][4]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
int b[3][4]={12, 2, 3, 4, 10, 6, 7, 11, 9, 5, 8, 1};
网友评论