簡體   English   中英

在類C ++中將靜態2D數組更改為動態數組

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

我有一個用'_'填充的二維char數組,我制作了一個靜態數組,我想將其更改為dynamic,以便您可以更改電路板的大小,是否需要在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM