我只是對從哪里開始感到困惑,比如這實際上是如何使用 2d 矢量繪制板子的。我沒有編輯任何代碼,下面的代碼是需要的。這是未完成的代碼,我不得不洗掉其他幾個函式,這樣我就可以先專注于創建電路板。我將如何使用 3x3 的破折號來創建這個板?
我將如何實際列印出 3x3 使其看起來像這樣:
- - -
- - -
- - -
我在想這樣的事情:
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
// Your code here
for (int i = 0; i < nRows; i ) {
}
}
但我不太確定如何繼續并列印出來。
// Tic-tac-toe board - user plays against computer; displays board after each move
#include <iostream>
#include <vector>
using namespace std;
const int nRows = 3;
const int nCols = 3;
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
// Your code here
}
// Game loop
int main() {
vector<vector<char>> board{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
displayBoard(board);
}
uj5u.com熱心網友回復:
每個人都vector知道自己的size(),因此您的顯示功能可能如下所示:
// 2D display of board contents
void displayBoard(const vector<vector<char>>& board) {
for (size_t i = 0; i < board.size(); i ) {
for (size_t j = 0; j < board[i].size(); j ) {
cout << board[i][j] << ' ';
}
cout << endl;
}
}
或者更簡單:
// 2D display of board contents
void displayBoard(vector<vector<char>>& board) {
for (const auto &vec : board) {
for (auto ch : vec) {
cout << ch << ' ';
}
cout << endl;
}
}
uj5u.com熱心網友回復:
對于你的問題,什么是
vector<vector<char>> board{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
做?它初始化board,一個vector的vectorS,使用串列初始化。每個{'-', '-', '-'}都是一個向量。vector串列中的三個s 提供了“ vectorof vectors”維數。
{'-', '-', '-'}
position 0 1 2 for each inner vector
{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
|_____________| |_____________| |_____________|
^ ^ ^
position 0 1 2 for the outer vector
因此,在訪問元素時,第一個索引選擇向量,第二個索引選擇該向量中的元素:
{ {'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
^ ^ ^
| | |
board[0][0] | |
board[1][1] |
board[2][2]
另一個答案向您展示了如何列印。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353734.html
標籤:C
上一篇:將Python腳本轉換為C
下一篇:在C#中根據浮點數驗證整數值
