多维数组

Multi-dimensional array

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

我需要创建一个函数,该函数具有一个参数,该参数是一个由用户指定的二维多维数组,例如

int function(int a, int b, int array[a][b])
{
 ...
}

我该如何在C++中做到这一点?

编译时维度是否已知?在这种情况下,将它们转换为模板参数,并通过引用传递数组:

template<int a, int b>
int function(int(&array)[a][b])
{
    ...
}

示例客户端代码:

int x[3][7];
function(x);
int y[6][2];
function(y);

假设在编译时维度未知,则用一维数组模拟二维数组:

int& getat(int x, int y, int r, int c, int *array) {return array[y*c+x];}
int function(int a, int b, int *array) {
    getat(4, 2, a, b, array) = 32; //array[4,2] = 32
}

或者,为了安全起见,将其全部封装在一个类中:

template <class T>
class array2d {
    std::vector<T> data;
    unsigned cols, rows;
public:
    array2d() : data(), cols(0), rows(0) {}
    array2d(unsigned c, unsigned r) : data(c*r), cols(c), rows(r) {}
    T& operator()(unsigned c, unsigned r) {
        assert(c<cols&&r<rows); 
        return data[r*cols+c];
    }
};

或者,最好使用Boost的多维数组,这将比普通人写的任何东西都要好。

我不确定这是否有效,因为你的问题和代码不一样,根据你的代码,函数可以有3个参数,所以这会有效:

int function(int a, int b, int** &array)
{
    array = new int*[a];
    for (int i =0;i<a;i++)
        array[i] = new int[b];
    // I don't know why you are returning int, probably doing something here....
}

然而,您的问题表明,您的函数只能接受一个参数,因此:

  1. 如果维度在编译时已知,那么Fred的答案是最好的(事实上它迷住了我!:))
  2. 如果没有,除了将所有这些值封装在一个对象中之外,我看不到任何可能的解决方案允许传递多个用户指定的值

像这样:

class Foo {
public:
    Foo(int d1, int d2)
    { a = d1; b = d2; }
    int a,b;
    int** array;
};
int function(Foo &f)
{
    f.array = new int*[f.a];
    for (int i = 0;i<f.a;i++)
        f.array[i] = new int[f.b];
    // I don't know why you are returning int, probably doing something here....
}

虽然我觉得这是个坏主意,但事实上function可以是一个无参数的方法:

class Foo {
public:
    Foo(int d1, int d2)
    { a = d1; b = d2; }
    void Create()   // Or could do this right in the Constructor
    {
        array = new int*[a];
        for (int i = 0;i<a;i++)
            array[i] = new int[b];
    }
private:
    int a,b;
    int** array;
};

尽管如此,这还是一个坏主意,因为你正在重新发明轮子,因为STL中有一个完美的类可以为你做所有的工作:

vector< vector<int> > v;    // Now v is a 2D array