【问题标题】:2D Dynamic Array in Classes C++ [duplicate]C ++类中的二维动态数组[重复]
【发布时间】:2018-02-06 12:56:40
【问题描述】:

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

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] = " ";
            }
}

我的声明可能有误,但我们将不胜感激

【问题讨论】:

  • board[row][col]; 应该做什么?您可能需要 std::vector&lt;std::vector&lt;std::string&gt;&gt; 而不是原始数组:string board[rowChoice][colChoice];
  • 请使用std::vector,省去很多时间和痛苦
  • 类定义指定对象布局。对象布局是静态不可更改的属性。如您所指,这样的数组如何应该是所有对象的固定属性?
  • 如果用户应该在运行时确定大小,您将无法使用静态数组(可以在编译时使用模板初始化)而是堆分配的动态数组(即使用 new 运算符)。如前所述,使用像 std::vector 这样的动态 stl 数组类型更容易。

标签: c++ arrays class multidimensional-array


【解决方案1】:

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

人们告诉您使用 STL 向量(来自 C++ 标准库)的原因是您不必管理在堆上存储标准二维数组,这意味着 new 和 delete 以及内存泄漏的可能性.

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

这就是我的意思:

#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 . . .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 2013-12-17
    • 2019-06-23
    • 2018-05-17
    • 2014-08-21
    • 2018-08-07
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多