Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a 2D array of variable size in a C++ class?

Tags:

c++

arrays

I am working on a tic tac toe program and I need to create a 2D array of variable size in a class. This is how I have it written now:

class ticTacToe
{
     public:
         ticTacToe();
         void display();
         bool moveIsValid();
     private:
         int rows;
         int cols;
         int board[rows][col];
}

I have the board being read in from a file in the constructor but I am not sure how to make it of variable size so that I can read in a board of any size and then access it outside of the class.

like image 521
gcccpp Avatar asked Dec 24 '22 22:12

gcccpp


1 Answers

"I have the board being read in from a file in the constructor but I am not sure how to make it of variable size so that I can read in a board of any size"

In c++ you use a std::vector instead a raw array like follows

class ticTacToe {
     public:
         ticTacToe();
         void display();
         bool moveIsValid();
     private:
         int rows;
         int cols;
         std::vector<std::vector<int>> board; // <<<<
};

The dynamic allocation can be applied as follows in a constructor:

ticTacToe(int rows_, int cols_) : rows(rows_), cols(cols_) {
    board.resize(rows,std::vector<int>(cols));
}

and then access it outside of the class

Well, I'm not sure that this is really a good idea, but you can simply add an accessor function for that member variable

 std::vector<std::vector<int>>& accBoard() { return board; }

The better design approach would be IMHO, to provide something like a separate function to read from a std::istream:

 void ticTacToe::readFromStream(std::istream& is) {
     // supposed the first two numbers in the file contain rows and cols
     is >> rows >> cols;
     board.resize(rows,std::vector<int>(cols));
     for(int r = 0; r < rows; ++r) {
         for(int c = 0; c < cols; ++c) {
             cin >> board[r][c];
         }
     }
 }

For real code you would check for input errors of course like

 if(!(is >> rows >> cols)) {
    // handle errors from input
 }
like image 131
πάντα ῥεῖ Avatar answered Feb 22 '23 22:02

πάντα ῥεῖ