c++ - 在具有可变长度的构造上创建二维数组

标签 c++ arrays

如何设置一个类,让我可以拥有一个私有(private)二维数组,其大小由通过构造函数传入的变量决定?

我已经试过了:

class World {
    private:
        const int WIDTH;
        const int HEIGHT;
        bool map[][];
    public:
        World(const int MAX_X, const int MAX_Y) : WIDTH(MAX_X), HEIGHT(MAX_Y) {
            map = new bool[WIDTH][HEIGHT];
        }
};

但是关于如何 declaration of ‘map’ as multidimensional array must have bounds for all dimensions except the first 我得到了一堆错误和 array size in operator new must be constant尽管它是。

我也试过这种方法,但也没用:

class World {
    private:
        const int WIDTH;
        const int HEIGHT;
        bool map[WIDTH][HEIGHT];
    public:
        World(const int MAX_X, const int MAX_Y) : WIDTH(MAX_X), HEIGHT(MAX_Y) {
            //map = new bool[WIDTH][HEIGHT];
        }
};

我得到一个 invalid use of non-static data member ‘World::WIDTH’const int WIDTH 上行和一个非常无用的error: from this location在 map 声明行上。

我做错了什么?

编辑: 我宁愿避免使用 vector ,因为我还没有在这门课上“学习”过它们。 (学到的我的意思是我知道如何使用它们,但教授没有讨论过它们并且不喜欢我们使用外部知识)

最佳答案

你可以使用 vector 。

class World
{
   typedef std::vector<bool> Tiles;
   typedef std::vector<Tiles> WorldMap;

   World(unsigned int width, unsigned int height)
   {
     for (unsigned int i = 0; i < width; i++)
     {
         m_map.push_back(Tiles(height));
     }
   }

private:
   WorldMap m_map;      
};

或者你可以使用模板,如果你在编译时知道世界的大小。

template <unsigned int Width, unsigned int Height>
class World
{
private:
  bool m_map[Width][Height];
};

或者您可以使用原始指针,因为二维数组实际上只是指向数组的指针的数组。

class World
{
   // Make sure you free this memory.
   World(unsigned int width, unsigned int height)
   {
     m_map = new bool*[width];
     for(unsigned int i = 0; i < height; ++i)
     {
        m_map[i] = new bool[width];
     }
   }

private:
   bool** m_map;
};

我建议使用前两个选项之一。

关于c++ - 在具有可变长度的构造上创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26792163/

相关文章:

python - 对整个复数数组进行插值

c# - 使用正则表达式将 double 替换为 float

c++ - 在 C++ 中表示关系

javascript - HTML 表单作为带有键值对的数组

通过在 C 中打印指针数组中的字符串元素来转换错误

c++ - C++中的动态数组声明

ios - prepareForSegue 清空我的 NSManagedObject 数组

c++ - c++中模板的问题

c++ - OpenCV 背景减法 c++

c++ - Boost graphviz自定义顶点标签