对于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;
}