[英]How to push_back something into a 2D Vector
I'm trying to code a Tic-Tac-Toe game and can't figure out how to push_back
a '+'
char whenever it's my turn. 我正在尝试编写Tic-Tac-Toe游戏的代码,并且无论何时轮到我都无法弄清楚如何push_back
一个'+'
char。
So whenever a player types for example "Oben links" which basically means Top left I want the game to check for the correct input and place a '+'
at the position the player picked. 因此,每当玩家输入例如“Oben链接”时,这基本上意味着左上角我希望游戏检查正确的输入并在玩家选择的位置放置一个'+'
。 What I am doing though does not seem to work. 我正在做什么虽然似乎不起作用。 Either it's not saving it or I'm using the wrong syntax. 它不是保存它或我使用错误的语法。
int main() {
vector < vector <char> > spielbrett(3, vector<char>('3'));
bool gewonnen = true;
string feld;
while (gewonnen) {
cout << "Position waehlen, z. B. Oben links oder Mitte Mitte usw. " << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << spielbrett[i][j] << " ";
if (j < 2) {
cout << " | ";
}
}
if (i < 2) {
cout << endl << " ------------ " << endl;
}
}
cout << endl << endl << endl;
cin >> feld;
if (feld == "Oben links") {
spielbrett[0].push_back('+');
}
else if (feld == "Oben mittig") {
}
else if (feld == "Oben rechts") {
}
else if (feld == "Mitte links") {
}
else if (feld == "Mitte mittig") {
}
else if (feld == "Mittig rechts") {
}
else if (feld == "Unten links") {
}
else if (feld == "Unten mittig") {
}
else if (feld == "Unten rechts") {
}
}
system("pause");
}
You do not want to use push_back
here. 你不想在这里使用push_back
。 Since the vector is already 3x3 thanks to 由于矢量已经是3x3,因此
vector < vector <char> > spielbrett(3, vector<char>('3'));
All you need to do is access the positions directly. 您需要做的就是直接访问这些职位。 So if you want the top left corner then you want 所以如果你想要左上角那么你想要的
spielbrett[0][0] = '+';
The bottom right would be 右下角是
spielbrett[2][2] = '+';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.