在 class C++ 中将静态二维数组更改为动态数组

Changing a static 2D array into a Dynamic array in a class C++

我有一个用“_”填充的二维字符数组,我制作了一个静态数组,我想将其更改为动态数组以便您可以更改板的大小,我是否需要分配一个指针在 public 中并且 int 是私密的?还是我必须完全制作一个新阵列?谢谢 :)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>


using namespace std;

class board
{

public:
    void makeBoard()
    {
        for (int i = 0; i < 11; yaxis++)
        {
            for (int j = 0; j < 11; xaxis++)
            {
                opening[i][j] = '_';
            }
        }
    }

private:
    char placement[11][11];
};

按照建议,std::vector 可能是正确的选择。这是一个可能对您有所帮助的小示例:

#include <vector>

class board
{

public:
    board(int x, int y)
    {
        resize(x, y);
    }

    void resize(int x, int y) 
    {
        // make sure input is OK
        mBoard.clear();
        for (int i = 0; i < x; ++i) 
            mBoard.emplace_back(std::vector<char>(y, '_'));
    }
private:
    std::vector<std::vector<char>> mBoard; // 2 dimensional std::vector
};

并由

创建
board my_board(11, 11);
my_board.resize(2, 10); // Resize afterwards