c ++创建二维数组_C ++中的二维数组

本文介绍了C++中的二维数组,包括如何初始化、打印和进行矩阵加法。通过示例代码详细展示了如何使用指针操作2D数组,并将其传递给函数。文章还涵盖了用户输入2D数组元素和使用2D数组进行矩阵加法的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 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
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 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
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
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:

输出

2D Array To Functions
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 array

    q保存第零个一维数组的基地址
  • 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://www.journaldev.com/36660/two-dimensional-array-in-c-plus-plus

c ++创建二维数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值