如何从 cpp 中的函数 return 二维数组

How to return a 2D array from a function in cpp

我正在尝试创建 2d 数组并希望 return 它在函数中...任何建议...我浏览了所有网站但一无所获..

double ** function() {

    double array[] [] ;
                /*code.............. */
    return array:
    ;
    }

最好使用 vector 就像评论中建议的 woz。但是使用数组你可以做到这一点。但首先你需要确定是谁创建了这个数组,它应该是删除它的那个file/class。一种安全的方法是不公开原始数组并使用函数访问它(请注意此代码不是线程安全的)。

class Array2D
{    
public:

    Array2D(int xSize, int ySize)
    {
        xS = xSize;
        yS = ySize;
        arr = new double*[xSize];
        for(int i = 0; i < xSize; ++i)
            arr[i] = new double[ySize];
    }

    bool GetData(int x, int y, double& value)
    {
        if(x < xS && y < yS)
        {
            value = arr[x][y];
            return true;
        }
        return false;
    }

    bool SetData(int x, int y, double value)
    {
        if(x < xS && y < yS)
        {
            arr[x][y] = value;
            return true;
        }
        return false;
    }

    ~Array2D()
    {
        for (int i = 0; i < xS; i++)
        {
            delete [] arr[i];
        }
        delete [] arr;
    }

private:
    //A default constructor here will prevent user to create a no initialized array
    Array2D(){};
    double** arr;
    int xS;
    int yS;
};