c ++创建二维数组

介绍 (Introduction)

A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It can be visualized as an array of arrays. The image below depicts a two-dimensional array.

C ++中的二维数组多维数组的最简单形式。 可以将其可视化为数组数组。 下图描绘了二维数组。

2D Array Representation
2D阵列表示

A two-dimensional array is also called a matrix. It can be of any type like integer, character, float, etc. depending on the initialization. In the next section, we are going to discuss how we can initialize 2D arrays.

二维数组也称为矩阵 。 根据初始化,它可以是任何类型,例如整数,字符,浮点数等。 在下一节中,我们将讨论如何初始化2D数组。

在C ++中初始化2D数组 (Initializing a 2D array in C++)

So, how do we initialize a two-dimensional array in C++? As simple as this:

那么,如何在C ++中初始化二维数组? 就这么简单:


int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
} ;

So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an array of arrays. Each element of the array is yet again an array of integers.

因此,正如您所看到的,我们初始化一个2D数组arr ,将42列作为数组数组。 数组的每个元素又是整数数组。

We can also initialize a 2D array in the following way.

我们还可以通过以下方式初始化2D数组。


int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};

In this case too, arr is a 2D array with 4 rows and 2 columns.

同样,在这种情况下, arr是具有4行2列的2D数组。

用C ++打印2D数组 (Printing a 2D Array in C++)

We are done initializing a 2D array, now without actually printing the same, we cannot confirm that it was done correctly.

我们已经完成了2D数组的初始化,现在还没有实际打印它,我们无法确认它是否正确完成了。

Also, in many cases, we may need to print a resultant 2D array after performing some operations on it. So how do we do that?

同样,在许多情况下,我们可能需要在对二维数组执行一些操作后打印它。 那么我们该怎么做呢?

The code below shows us how we can do that.

下面的代码向我们展示了如何做到这一点。


#include<iostream>
using namespace std;
main( )
{  int arr[4][2] = {{ 10, 11 },{ 20, 21 },{ 30, 31 },{ 40, 41 }} ;int i,j;cout<<"Printing a 2D Array:\n";for(i=0;i<4;i++){for(j=0;j<2;j++){cout<<"\t"<<arr[i][j];}cout<<endl;}
}

Output:

输出

Printing A 2D Array
打印二维阵列

In the above code,

在上面的代码中,

  • We firstly initialize a 2D array, arr[4][2] with certain values,首先,我们使用特定值初始化2D数组arr[4][2]
  • After that, we try to print the respective array using two for loops,之后,我们尝试使用两个for循环打印相应的数组,
  • the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array,外部的for循环遍历行,而内部的for循环遍历2D数组的列,
  • So, for each iteration of the outer loop, i increases and takes us to the next 1D array. Also, the inner loop traverses over the whole 1D array at a time,因此,对于外循环的每次迭代, i增加并带我们进入下一个1D数组。 而且,内部循环一次遍历整个一维数组,
  • And accordingly, we print the individual element arr[ i ][ j ].因此,我们打印单个元素arr[ i ][ j ]

将2D数组元素作为用户输入 (Taking 2D Array Elements As User Input)

Previously, we saw how we can initialize a 2D array with pre-defined values. But we can also make it a user input too. Let us see how

之前,我们看到了如何使用预定义的值初始化2D数组。 但是我们也可以将其作为用户输入 。 让我们看看


#include<iostream>
using namespace std;
main( )
{  int  s[2][2];int  i, j;cout<<"\n2D Array Input:\n";for(i=0;i<2;i++){for(j=0;j<2;j++){cout<<"\ns["<<i<<"]["<<j<<"]=  ";cin>>s[i][j];}} cout<<"\nThe 2-D Array is:\n";for(i=0;i<2;i++){for(j=0;j<2;j++){cout<<"\t"<<s[i][j];}cout<<endl;}
}

Output:

输出

2D Array User Input
2D阵列用户输入

For the above code, we declare a 2X2 2D array s. Using two nested for loops we traverse through each element of the array and take the corresponding user inputs. In this way, the whole array gets filled up, and we print out the same to see the results.

对于上面的代码,我们声明一个2X2 2D数组s 。 使用两个嵌套的for循环,我们遍历数组的每个元素并获取相应的用户输入。 这样,整个数组被填满,我们将其打印出来以查看结果。

在C ++中使用二维数组进行矩阵加法 (Matrix Addition using Two Dimensional Arrays in C++)

As an example let us see how we can use 2D arrays to perform matrix addition and print the result.

作为示例,让我们看看如何使用2D数组执行矩阵加法并打印结果。


#include<iostream>
using namespace std;
main()
{  int  m1[5][5], m2[5][5], m3[5][5];int  i, j, r, c;cout<<"Enter the no.of rows of the matrices to be added(max 5):";cin>>r;cout<<"Enter the no.of columns of the matrices to be added(max 5):";cin>>c;cout<<"\n1st Matrix Input:\n";for(i=0;i<r;i++){for(j=0;j<c;j++){cout<<"\nmatrix1["<<i<<"]["<<j<<"]=  ";cin>>m1[i][j];}} cout<<"\n2nd Matrix Input:\n";for(i=0;i<r;i++){for(j=0;j<c;j++){cout<<"\nmatrix2["<<i<<"]["<<j<<"]=  ";cin>>m2[i][j];}} cout<<"\nAdding Matrices...\n";for(i=0;i<r;i++){for(j=0;j<c;j++){m3[i][j]=m1[i][j]+m2[i][j];}} cout<<"\nThe resultant Matrix is:\n";for(i=0;i<r;i++){for(j=0;j<c;j++){cout<<"\t"<<m3[i][j];}cout<<endl;} }

Output:

输出

Matrix Addition Using 2D Arrays
使用2D阵列进行矩阵加法

Here,

这里,

  • We take two matrices m1 and m2 with a maximum of 5 rows and 5 columns. And another matrix m3 in which we are going to store the result,我们取两个矩阵m1m2 ,最多5行5列。 还有另一个要存储结果的矩阵m3
  • As user inputs, we took the number of rows and columns for both the matrices. Since we are performing matrix addition, the number of rows and columns should be the same for both the matrices,作为用户输入,我们获取了两个矩阵的行数和列数。 由于我们正在执行矩阵加法,因此两个矩阵的行数和列数应相同,
  • After that, we take both the matrices as user inputs, again using nested for loops,之后,我们将两个矩阵都作为用户输入,再次使用嵌套的for循环,
  • At this point, we have both the matrices m1 and m2,此时,我们同时拥有矩阵m1m2
  • then we traverse through the m3 matrix, using two for loops and update the respective elements m3[ i ][ j ] by the value of m1[i][j]+m2[i][j]. In this way, by the end of the outer for loop, we get our desired matrix,然后我们遍历m3矩阵,使用两个for循环,并通过m1[i][j]+m2[i][j]的值更新各个元素m3[ i ][ j ] m1[i][j]+m2[i][j] 。 这样,在外部for循环结束时,我们得到了所需的矩阵,
  • At last, we print out the resultant matrix m3.最后,我们打印出结果矩阵m3。

指向C ++中的2D数组的指针 (Pointer to a 2D Array in C++)

If we can have a pointer to an integer, a pointer to a float, a pointer to a char, then can we not have a pointer to an array? We certainly can. The following program shows how to build and use it.

如果我们可以有一个指向整数的指针,一个浮点数的指针,一个char的指针,那么我们不能有一个指向数组的指针吗? 我们当然可以。 以下程序显示了如何构建和使用它。


#include<iostream>
using namespace std;
/* Usage of pointer to an array */
main( )
{  int  s[5][2] = {{1, 2},{1, 2},{1, 2},{1, 2}} ;int (*p)[2] ;int  i, j;for (i = 0 ; i <= 3 ; i++){p=&s[i];cout<<"Row"<<i<<":";for (j = 0; j <= 1; j++)cout<<"\t"<<*(*p+j);cout<<endl;} }

Output:

输出

2D Array Pointer
二维数组指针

Here,

这里,

  • In the above code, we try to print a 2D array using pointers,在上面的代码中,我们尝试使用指针打印2D数组,
  • As we earlier did, at first we initialize the 2D array, s[5][2]. And also a pointer (*p)[2], where p is a pointer which stores the address of an array with 2 elements,正如我们之前所做的,首先我们初始化2D数组s[5][2] 。 还有一个指针(*p)[2] ,其中p是一个指针,用于存储包含2个元素的数组的地址,
  • As we already said, we can break down a 2D array as an array of arrays. So in this case, s is actually an array with 5 elements, which further are actually arrays with 2 elements for each row.正如我们已经说过的,我们可以将2D数组分解为一个数组数组。 因此,在这种情况下,s实际上是一个包含5个元素的数组,进一步来说,实际上是每行包含2个元素的数组。
  • We use a for loop to traverse over these 5 elements of the array, s. For each iteration, we assign p with the address of s[i],我们使用for循环遍历数组s的这5个元素。 对于每次迭代,我们为p分配s[i]的地址,
  • Further, the inner for loop prints out the individual elements of the array s[i] using the pointer p. Here, (*p + j) gives us the address of the individual element s[i][j], so using *(*p+j) we can access the corresponding value.此外,内部for循环使用指针p打印出数组s [i]的各个元素。 这里, (*p + j)给出了单个元素s [i] [j]的地址,因此使用*(*p+j)我们可以访问相应的值。

将二维数组传递给函数 (Passing 2-D Array to a Function)

In this section, we are going to learn how to pass a 2D array to any function and access the corresponding elements. In the code below, we pass the array a, to two functions show() and print() which prints out the passed 2D array.

在本节中,我们将学习如何将2D数组传递给任何函数并访问相应的元素。 在下面的代码中,我们将数组a传递给两个函数show()print() ,以打印出传递的2D数组。


#include<iostream>
using namespace std;   void show(int (*q)[4], int  row, int  col)
{int  i, j ;for(i=0;i<row;i++){for(j=0;j<col;j++)cout<<"\t"<<*(*(q + i)+j); cout<<"\n";}  cout<<"\n";
} void print(int  q[][4], int row, int col)
{int  i, j; for(i=0;i<row;i++){   for(j=0;j<col;j++)cout<<"\t"<<q[i][j];cout<<"\n";}cout<<"\n";
}int main()
{int  a[3][4] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21} ; show (a, 3, 4);print (a, 3, 4);return 0;
}

Output:

输出

Passing 2D Array To Functions
将2D数组传递给函数

Here,

这里,

  • In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration int (*q)[4],在show( )函数中,我们通过声明int (*q)[4]将q定义为指向4个整数数组的指针,
  • q holds the base address of the zeroth 1-D arrayq保存第零个一维数组的基地址
  • This address is then assigned to q, an int pointer, and then using this pointer all elements of the zeroth 1D array are accessed.然后将该地址分配给一个int指针q ,然后使用该指针访问第1个1D数组的所有元素。
  • Next time through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D array. This is because q is a pointer to the zeroth 1-D array and adding 1 to it would give us the address of the next 1-D array. This address is once again assigned to q and using it all elements of the next 1-D array are accessed下次通过循环,当i取值为1时 ,表达式q + i获取第一个1-D数组的地址。 这是因为q是指向第零个一维数组的指针,将其加1将为我们提供下一个一维数组的地址。 将该地址再次分配给q,并使用它访问下一个1-D数组的所有元素
  • In the second function print(), the declaration of q looks like this: int q[][4] ,在第二个函数print()q的声明如下所示: int q[][4]
  • This is same as int (*q )[4], where q is a pointer to an array of 4 integers. The only advantage is that we can now use the more familiar expression q[i][j] to access array elements. We could have used the same expression in show() as well but for better understanding of the use of pointers, we use pointers to access each element.这与int(* q)[4]相同 ,其中q是指向4个整数的数组的指针。 唯一的好处是我们现在可以使用更熟悉的表达式q[i][j]访问数组元素。 我们也可以在show()使用相同的表达式,但是为了更好地理解指针的使用,我们使用指针访问每个元素。

结论 (Conclusion)

So, in this article, we discussed two-dimensional arrays in C++, how we can perform various operations as well as its application in matrix addition. For any further questions feel free to use the comments.

因此,在本文中,我们讨论了C ++中的二维数组 ,以及如何执行各种运算及其在矩阵加法中的应用。 对于任何其他问题,请随时使用注释。

参考资料 (References)

  • https://en.wikipedia.org/wiki/Array_data_structurehttps://zh.wikipedia.org/wiki/Array_data_structure
  • https://www.journaldev.com/30808/arrays-in-chttps://www.journaldev.com/30808/arrays-in-c

翻译自: https://www.journaldev.com/36660/two-dimensional-array-in-c-plus-plus

c ++创建二维数组

c ++创建二维数组_C ++中的二维数组相关推荐

  1. delphi7存储过程传入数组_C++中的指针、数组指针与指针数组、函数指针与指针函数...

    本文从初学者的角度,深入浅出地详解什么是指针.如何使用指针.如何定义指针.如何定义数组指针和函数指针,并给出对应的实例演示:接着,区别了数组指针与指针数组.函数指针与指针函数:最后,对最常混淆的引用传 ...

  2. 求出千位数上的数加百位数上的数等于十位数上的数加个位数上的数的个数cnt,再把所有满足条件的四位数依次存入数组b中,然后对数组b中的四位数按从大到小的顺序进行排序。

    已知数据文件IN13.DAT中存有300个四位数,并已调用读函数readDat()把这些数存入数组a中,请编制一个函数jsValue(),其功能是:求出千位数上的数加百位数上的数等于十位数上的数加个位 ...

  3. 求出所有这些四位数是素数的个数cnt,再把所有满足此条件的四位数依次存入数组b中,然后对数组b中的四位数按从小到大的顺序进行排序

    已知数据文件IN14.DAT中存有300个四位数,并已调用读函数readDat()把这些数存入数组a中.请编制一个函数jsValue(),其功能是:求出所有这些四位数是素数的个数cnt,再把所有满足此 ...

  4. 数组x中数据复制到数组y中,重复的数据只存储一次,最后输出y;计算x中数据的平均值ave及大于平均值的元素个数n。c++实现

    题目描述 编程序,实现如下功能: (1)定义两个一维数组x,y,不超过50个元素. (2)从键盘输入k个整数到数组x中. (3)计算x中数据的平均值ave及大于平均值的元素个数n并输出. (4)将数组 ...

  5. scala中的二维数组_Scala中的多维数组

    scala中的二维数组 多维数组 (Multi-dimensional arrays) An Array that stores data in the form multidimensional m ...

  6. java不等长二维数组_Java中关于二维数组的理解与使用

    今天练习的时候遇到一个题目,题目需求是这样的: 需求说明: 根据3个班各5名学生某门课程的成绩,正确使用二维数组计算如图所示3个班各自的总成绩 分析: 要实现这个功能需要存储两个信息: 一个是班级信息 ...

  7. python中的二维数组_Python中的二维数组实例(list与numpy.array)

    关于python中的二维数组,主要有list和numpy.array两种. 好吧,其实还有matrices,但它必须是2维的,而numpy arrays (ndarrays) 可以是多维的. 我们主要 ...

  8. 二维数组排序 java_java中的二维数组排序是怎样的?实例分享

    近些年随着科学技术水平的不断进步与发展,越来越多的人开始意识到java编程语言的重要性.也开始主动的学习这门语言.今天就来为大家介绍一些java中的基础知识,也就是java中的二维数组排序是怎样的?一 ...

  9. python二维元组_python中读入二维csv格式的表格方法详解(以元组/列表形式表示)

    如何去读取一个没有表头的二维csv文件(如下图所示)? 并以元组的形式表现数据: ((1.0, 0.0, 3.0, 180.0), (2.0, 0.0, 2.0, 180.0), (3.0, 0.0, ...

最新文章

  1. SQL2005客户端连接到SQL2000服务器存在的问题
  2. Jdon框架开发指南
  3. AAAI 2018 论文 | 蚂蚁金服公开最新基于笔画的中文词向量算法
  4. Android 应用内更新 Support in-app updates [GP官方支持]
  5. mybatis报错(三)报错Result Maps collection does not contain value for java.lang.Integer解决方法...
  6. 基于ObjectCache的应用
  7. Java设计模式-工厂模式
  8. QGIS 3.0 使用教程
  9. 如何将影像地图转换为国家2000坐标系
  10. 一个30岁工控人的自白
  11. python3爬取教务系统的个人学期课程表(无头谷歌浏览模拟登录)
  12. 电脑如何设置uefi启动 电脑设置uefi启动方法
  13. I/O设备和CPU之间数据传送控制方式
  14. 【PCB】Altium Designer PCB规则配置
  15. Glide加载相同URL时由于缓存无法更新图片的问题
  16. 期末复习【计算机组成原理】
  17. 当黑夜自此笼罩-白夜行之感想一二
  18. Pyramid of Glasses
  19. Java面试题之常见十五种异常有哪些?
  20. java程序设计第三版课后答案张思民

热门文章

  1. [转载] python - map()解析
  2. [转载] Python ascii()函数
  3. [转载] Python: ljust()|rjust()|center()字符串对齐
  4. Python 基础课程第四天
  5. 带新手玩转MVC——不讲道理就是干(下)
  6. 洛谷——P4053 [JSOI2007]建筑抢修
  7. C# XXX.XmlSerializers”的程序集未能加载到..
  8. 【例题 7-2 UVA - 11059】Maximum Product
  9. java 通过eclipse编辑器用mysql尝试 连接数据库
  10. 冷知识 —— 文学(名与字)