Create 2D array using size from parameters in C++

2020-01-30 01:58发布

问题:

I am trying to create a simple 2D array with the size being the parameters passed by the method. In C# we would have something like this:

float[,] GenerateNoiseMap(int mapWidth, int mapHeight){
     float noiseMap[,] = new float[mapWidth, mapHeight];
     return noiseMap;
}

Any idea how I can create a 2D array and return it in C++? So far the compiler gives me an error that the size has to be a constant value, and I want the values to be what the method parameters are

回答1:

I like a simple wrapper around a 1D vector:

#include <vector>

class Matrix
{
private:
    size_t rows, columns;
    std::vector<double> matrix;
public:
    Matrix(size_t numrows, size_t numcols) :
            rows(numrows), columns(numcols), matrix(rows * columns)
    {
    }

    double & operator()(size_t row, size_t column)
    {
        return matrix[row * columns + column]; // note 2D coordinates are flattened to 1D
    }

    double operator()(size_t row, size_t column) const
    {
        return matrix[row * columns + column];
    }

    size_t getRows() const
    {
        return rows;
    }
    size_t getColumns() const
    {
        return columns;
    }
};

Documentation for std::vector

Usage:

Matrix noiseMap(mapWidth, mapHeight);


回答2:

You cannot have a 2D C-like array with a dynamic size on both dimensions in C++. C# arrays look a bit like them, but they're not the same thing at all.

I recommend boost::multi_array for this:

#include <boost/multi_array.hpp>

boost::multi_array<float, 2> GenerateNoiseMap(int mapWidth, int mapHeight) {
    return boost::multi_array<float, 2>{boost::extents[mapWidth][mapHeight]};
}


回答3:

float ** create_matrix(size_t m, size_t n)
{
    float ** answer = new float*[m];
    for (size_t i =0; i < m; i++)
        answer[i] = new float[n];
    return answer;
}


标签: c++ arrays