【问题标题】:Initialize array with length variable passed to method使用传递给方法的长度变量初始化数组
【发布时间】:2018-03-14 04:12:06
【问题描述】:

我正在开发一个程序,对于其中一个类,我将宽度和高度传递给构造函数,然后构造函数使用它们来初始化一个数组以临时保存一些数据。

class NoiseDrawable : public Drawable {
    public:
        NoiseDrawable(const int width, const int height, Color color) : Drawable(width, height) {
            float heightMap[width][height];

            ....

现在的问题是我在使用宽度和高度初始化数组时遇到错误:

expression must have constant value

现在我明白我为什么会收到这个错误了,这完全有道理。我不明白的是为什么即使将传递的整数更改为常数后我仍然得到它!

我该如何解决这个问题?

【问题讨论】:

  • VLA 不是标准的 C++。请改用std::vector
  • 呃,我开始猜测太多了,但希望避免使用向量,因为处理二维数据会很麻烦
  • 您可以使用std::vector<std::vector<float>> heightMap(width,std::vector<float>(height));
  • 一维向量很容易使用,并且像二维一样访问它也非常容易。 "size_t 1d_IndxFrom(int r, int c) { return static_cast((r * maxCol) + c); }"

标签: c++ arrays methods


【解决方案1】:

如果你想避免矢量,你可以试试这个。增加了复杂性并且有点难看

float** heightMap = new int*[width];//create array of pointers (width many)

for(int i = 0; i < rowCount; ++i)
    heightMap[i] = new int[height];//add turn each pointer into a float array (height long)

编辑这需要手动清理内存

【讨论】:

  • 不仅要手动管理内存,而且由于数据不连续,这甚至和原来的方法都不一样。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 2011-01-26
  • 2022-07-19
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 2020-07-13
  • 2021-03-26
相关资源
最近更新 更多