本文介绍了使用 C++ 中参数的大小创建二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个简单的二维数组,其大小是方法传递的参数.在 C# 中,我们会有这样的事情:
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;
}
知道如何创建二维数组并在 C++ 中返回它吗?到目前为止,编译器给了我一个错误,即大小必须是一个常量值,我希望这些值是方法参数的值
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
推荐答案
我喜欢一维向量的简单包装:
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;
}
};
用法:
Matrix noiseMap(mapWidth, mapHeight);
这篇关于使用 C++ 中参数的大小创建二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!