Search code examples
c++vectorvisual-c++stdvector

C++ vector issue


I'm trying to create a Tic-Tac-Toe project for a lesson in Codecademy.

The problem I have is that they never showed us how to create a 2D vector, so I looked it up online, and basically this is what I created for my file so far:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void intro(){
    cout << "Let's play a game of Tic-Tac-Toe!\n Decide who goes first and enter your letters accordingly.\n First to match three letters in a row wins!\n\n";
}

int i;
int j;

int main(){

    intro();

    vector<vector<int>>board{{1,2,3},{4,5,6}};
    for(int i = 0; i < board.size(); i++){
        for (int j = 0; j < board.size(); j++)
            cout << board[i][j] << " " << endl;
    }

    return 0;
}

I can't get the actual 2D vector to print to the terminal. I plan on adjusting the input values later with the game, so I can't use an array (I believe). Any advice is appreciated.


Solution

  • For a 1D matrix, we initialize it by vector<int> whose size can be extracted by just getting the size of the vector by board.size().

    Now, in your case where it's a 2D matrix, the size for rows and columns may differ. In that case, you can usually extract the row size by easily getting the outer matrix size by board.size(), and the column size by extracting the internal vector size board[0].size() (if we assume the columns on all row level are same). Otherwise, if you want to get the column size at every row, you can get it by board[i].size() where i is the row index.

    Similarly, for 3D it will be vector<vector<vector<int>>>, and so on...

    Below is the corrected code :

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    void intro() {
        cout << "Let's play a game of Tic-Tac-Toe!\n Decide who goes first and enter your letters accordingly.\n First to match three letters in a row wins!\n\n";
    }
    
    int main() {
        intro();
       
        // 2x3 matrix here, rows = 2 & columns = 3
        vector<vector<int>> board{{1, 2, 3}, {4, 5, 6}};
    
        // iterating on each row
        for (int i = 0; i < board.size(); i++) {
            // iterating on each column within row
            for (int j = 0; j < board[0].size(); j++) { // Change to board[i].size() or board[0].size()
                cout << board[i][j] << " ";
            }
            cout << endl; // line break on moving to next row
        }
        return 0;
    }