将2D数组传递到功能

Pass 2D array to function

本文关键字:功能 2D 数组      更新时间:2023-10-16

我是编程的新手。

用户将输入2D数组的大小,然后我想将此数组传递给功能。我该怎么做?

有两种方法可以实现您的目标。

第一种方法正在使用动态分配的C风格数组。除非您被迫支持现有代码,否则您不应在C 中这样做。但是在这种情况下,最好考虑重构。

第二路正在使用std::vector。此类将低级操作封装在记忆中。它会使您摆脱许多潜在的错误。

要向您展示std::vector的优势,我已经编写了两个程序。他们输入2D数组的大小(另一种方式称为矩阵)并创建它。

使用C风格阵列创建矩阵,请求大量的代码和指针。为了简单起见,以下代码无法处理异常。在实际代码中,您应该这样做以避免内存泄漏,但是代码会变得更加困难。

#include <iostream>
#include <cstddef>
using namespace std;
void function(int** matrix, size_t nrows, size_t ncols)
{
}
int main()
{
    size_t nrows;
    size_t ncols;
    cin >> nrows >> ncols;
    // allocate memory for matrix
    int** matrix = new int*[nrows];
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = new int[ncols];
    function(matrix, nrows, ncols);
    // release memory
    for (size_t i = 0; i < nrows; ++i)
        delete[] matrix[i];
    delete[] matrix;
}

因此,在C 中,使用std::vector会更容易。由于std::vector是一类,因此具有构造函数和驱动器封装分配和释放内存。

#include <iostream>
#include <vector>
using namespace std;
void function(vector<vector<int>>& matrix)
{
}
int main()
{
    size_t nrows;
    size_t ncols;
    cin >> nrows >> ncols;
    // create matrix
    vector<vector<int>> matrix(nrows);
    for (size_t i = 0; i < nrows; ++i)
        matrix[i] = vector<int>(ncols);
    // you don't even need to pass sizes of matrix
    function(matrix);
    // automatically called destructor of matrix releases memory
}