简体   繁体   中英

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.

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. 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. Since the vector is already 3x3 thanks to

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] = '+';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM