【问题标题】:How to return a 2D array from a function in cpp如何从cpp中的函数返回二维数组
【发布时间】:2019-04-19 20:48:58
【问题描述】:

我正在尝试创建 2d 数组并希望将其返回到函数中...任何建议...我浏览了所有站点但一无所获..

double ** function() {

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

【问题讨论】:

  • 为什么不使用std::vector<std::vector<T>>
  • Return a 2d array from a function 的可能重复项。要点是您必须动态分配才能返回原始数组,但使用向量或类似的更容易。
  • 我只使用了向量。但他们特别提到使用数组...
  • 这是不可能的。最接近的方法是让您的调用者提供数组,除非您想动态分配它并相信调用者会记得释放内存。

标签: c++ arrays function multidimensional-array 2d


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 2012-01-26
    • 2011-07-09
    • 2021-03-29
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多