类C ++中的2D动态数组

时间:2017-08-29 07:08:38

标签: c++ arrays class multidimensional-array

我很难理解如何在类中声明一个数组并在同一个类的所有函数中使用它。数组大小取决于用户。

class Game{
 public:
    void createBoard();
    void gameStart();
    void inputBoard();
    void inputBoardSize();
    Game(int,int);


private:
    int rowChoice;
    int colChoice;
    int playerTurnRow;
    int playerTurnCol;
    string playerTurn;
    string board[rowChoice][colChoice];

};

Game::Game(int row,int col){
    rowChoice = row;
    colChoice = col;
    playerTurnRow = 0;
    playerTurnCol = 0;
    playerTurn = "R";
    board[row][col];
}

void Game::createBoard(){


        for (int arrayRow = 0;arrayRow < rowChoice;arrayRow++){
            for (int arrayCol = 0;arrayCol < colChoice;arrayCol++){
                board[arrayRow][arrayCol] = " ";
            }
}

我的声明可能有误,但任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:0)

您的语法很有意义,但不是C ++的工作方式。标准数组只能是固定大小(在编译时定义,不是动态生成的),除非您将该数组存储在堆上。

人们告诉你使用STL向量(来自C ++标准库)的原因是因为你不必管理在堆上存储标准的2d数组,这意味着新的和删除以及内存泄漏的可能性

向量还允许你调整大小,为你做边界检查,并且通常同样有效,因为它们以相同的方式存储数组(连续地存储在内存中)。

这就是我的意思:

#include <iostream>
#include <vector>
#include <algorithm>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

void standard_array_example(int r, int c)
{
  // here you are responsible for managing memory yourself
  // allocate an array on the heap, r * c sized
  char *board = new char[r * c];

  // fill the board with x's
  std::fill_n(board, r * c, 'x');

  for (int i = 0; i < r; i++)
  {
    for (int k = 0; k < c; k++)
    {
      cout << board[i * c + k] << " ";
    }
    cout << endl;
  }

  // you must manually free your memory, or else there is a leak
  delete[] board;
}

void vector_example(int r, int c)
{
  // here, your memory is managed for you. when board goes out of scope
  // it is destroyed. the scope here is the end of the function
  vector<vector<char>> board;
  for (int i = 0; i < r; i++)
  {
    board.push_back(vector<char>(c, 'x'));
  }

  for (auto r : board)
  {
    for (auto c : r)
    {
      cout << c << " ";
    }
    cout << endl;
  }
}

int main()
{
  int r, c;
  cin >> r;
  cin >> c;

  standard_array_example(r, c);
  cout << endl;
  vector_example(r, c);

  system("PAUSE");

  return 0;
}

两者的功能相同:

5
5
x x x x x
x x x x x
x x x x x
x x x x x
x x x x x

x x x x x
x x x x x
x x x x x
x x x x x
x x x x x
Press any key to continue . . .