代码之家  ›  专栏  ›  技术社区  ›  ultimatejooe

C++矢量问题

  •  0
  • ultimatejooe  · 技术社区  · 1 年前

    我正试图为Codecademy的一节课创建一个Tic-Tac-Toe项目。

    我遇到的问题是,他们从未向我们展示过如何创建2D矢量,所以我在网上查找了它,基本上这就是我迄今为止为文件创建的内容:

    #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;
    }
    

    我无法将实际的2D矢量打印到终端。我计划稍后在游戏中调整输入值,所以我不能使用数组(我相信)。欢迎提出任何建议。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Parv    1 年前

    对于1D矩阵,我们通过以下方式对其进行初始化 vector<int> 其大小可以通过以下公式获得向量的大小来提取 board.size() .

    现在,在您的情况下,它是一个2D矩阵,行和列的大小可能不同。在这种情况下,通常可以通过以下方式轻松获取外部矩阵大小来提取行大小 board.size() ,以及通过提取内部向量大小来确定列大小 board[0].size() (如果我们假设所有行级别上的列都相同)。否则,如果您想获得每行的列大小,可以通过 board[i].size() 其中i是行索引。

    同样,对于3D vector<vector<vector<int>>> 等等

    以下是更正后的代码:

    #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;
    }