【问题标题】:how to pass dynamic 2d array to a function without using the pointers?如何在不使用指针的情况下将动态二维数组传递给函数?
【发布时间】:2017-10-03 17:21:18
【问题描述】:

我试过了,但它不起作用! 谁能帮帮我,这很重要:(

#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);
}

【问题讨论】:

  • int a[n][n]; 是 VLA 而不是标准 C++。
  • 你应该切换参数。如果之前写int n,可以使用数组大小​​中的值:void read(int n, int a[][n])
  • 您的 a[][] 声明冲突
  • 它是c++。为什么不使用std::vector?它专为此类情况而设计。
  • @RohanKumar all a 在不同的范围内,所以没有冲突。

标签: c++ arrays function parameters variable-length-array


【解决方案1】:

通过引用传递数组的不清楚的语法是:

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

导致

#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);
}

但你可能更喜欢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】:

因为它被标记为 C++。我想建议使用std::vector。它是一个非常有用的动态容器。您可以调整它的大小,清除它,轻松填充它。一旦您了解了它的基本用法,它们将在您未来的 C++ 开发中非常方便。我稍微修改了你的代码:

#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);
}

与原始数组相比,它们具有许多优点,例如可以轻松初始化,假设您想将所有初始化为零:

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

您不必担心在传入函数时添加数组大小。 vector 可以轻松处理:

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

此外,还添加了标准模板库的方法,例如fillswap。许多操作都可以轻松处理。

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2020-10-11
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多