how to pass dynamic 2d array to a function without using the pointers?

老子叫甜甜 提交于 2019-12-12 04:16:29

问题


I tried this but it is not working ! can any one help me please this is very important :(

#include <iostream>
using namespace std;
int a[100][100];

void read(int a[][100],int n)
{
  int i,j;
  for(i=0;i<n;i++)
       for(j=0;j<n;j++)
     cin>>a[i][j];
}

int main ()
{
    int n;
    cin>>n;
    int a[n][n];
   read(a,n);
}

回答1:


The unclear syntax to pass array by reference is:

void read(int (&a)[100][100], int n)

resulting in

#include <iostream>

void read(int (&a)[100][100], int n)
{
  for(int i = 0; i < n; i++)
       for(int j = 0; j < n; j++)
           std::cin >> a[i][j];
}

int main ()
{
    int n;
    std::cin >> n;
    int a[100][100];
    read(a, n);
}

but you might prefer std::vector:

#include <iostream>
#include <vector>

void read(std::vector<std::vector<int>> &mat)
{
    for (auto& v : mat) {
        for (auto& e : v) {
            std::cin >> e;
        }
    }
}

int main ()
{
    int n;
    std::cin >> n;
    std::vector<std::vector<int>> mat(n, std::vector<int>(n));
    read(mat);
}



回答2:


Since this is tagged C++. I'd like to suggest usage of std::vector. It's dynamic container which is very useful. You can resize it, clear it fill it with ease. Once you understand it's basic usage, they would come really handy in your future C++ development. I modified your code slightly:

#include <iostream>
#include <vector>
using namespace std;

void read(vector<vector<int> >& arr,int n)
{
  int i,j;
  for(i=0;i<n;i++)
       for(j=0;j<n;j++)
           cin>>arr[i][j];
}
int main ()
{
    int N;
    cin>>N;
    vector<vector<int> > arr(N, vector<int>(N));
    read(arr, N);
}

They have many advantages over the primitive arrays like they can be initialized easily, suppose you want to initialize all to zero :

vector<vector<int> > arr(N, vector<int>(N, 0));

You don't have to worry about adding the array size whenever passing in functions. vector can easily handle this:

for(i = 0; i < arr.size(); i++) {
  for(j = 0; j < arr[i].size(); j++) {
    // do stuff
  }
}

Moreover with the added methods of the Standard template library like fill, swap. Many operations can be handled easily.



来源:https://stackoverflow.com/questions/43801347/how-to-pass-dynamic-2d-array-to-a-function-without-using-the-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!