矢量下标超出范围:(

时间:2015-11-10 22:06:31

标签: c++ vector visual-studio-2015

所以我是一个相对较新的c ++程序员。我刚刚将这段代码作为我正在研究的面向对象的tic-tac-toe的一部分。它在Visual Studio社区2015中,当代码应该检查获胜者时,我得到错误"向量下标超出范围"。它很糟糕,很糟糕。

int Board::Win_Check()
{
    int ar[8][3] = {
        { 0, 1, 2 },
        { 3, 4, 5 },
        { 6, 7, 8 },
        { 0, 3, 6 },
        { 1, 4, 7 },
        { 2, 5, 8 },
        { 0, 4, 8 },
        { 2, 4, 6 } };

    int winner1 = 0;
    int winner2 = 0;

    bool winner1won = false;
    bool winner2won = true;

    for (int i = 0; i < 9; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            if (m_board[ar[i][j]] == 'X')
            {
                ++winner1;
            }
            else if (m_board[ar[i][j]] == 'Y')
            {
                ++winner2;
            }

            if (winner1 != 3)
            {
                winner1 = 0;
            }
            else
            {
                winner1won = true;
            }

            if (winner2 != 3)
            {
                winner2 = 0;
            }
            else
            {
                winner2won = true;
            }
        }
    }

    int return_type;

    if (winner1won == true)
    {
        return_type = 1;
    }
    else if (winner2won == true)
    {
        return_type = 2;
    }
    else
    {
        return_type = 0;
    }

    return return_type;
}

1 个答案:

答案 0 :(得分:1)

你的指数明显超出范围

 for (int i = 0; i < 9; ++i) {

应该是

 for (int i = 0; i < 8; ++i) {
                  // ^

声明数组

int ar[8][3] = {
    // ^