首页 > 解决方案 > 当我尝试编译时,我不断收到消息向量下标超出范围

问题描述

string getName()  { return name; }
string getE1()  { return enemy1; }
string getE2()  { return enemy2; }
string getE3()  { return enemy3; }

bool isEnemy(string check) {
    if (check == enemy1 || check == enemy2 || check == enemy3)

//如果被检查的名字是这个骑士的敌人返回true;否则返回假;}

int Candidate(Knight b) {//'b' is an enemy of 'a' who is in the seat before 'b'(ie. b seat=2 a seat=1
    int toSwap = b.seatingPos;//toSwap holds seating pos # of 'b'
    int checkFriends = (toSwap - 1);//holds seating pos of 'a'
    string nameA = table[checkFriends].getName();
    for (int i = 0; i < 8; i++) {
        if (table[i].isEnemy(nameA) || table[i].getName() == nameA) //if not enemies, then must be friends
        {
            continue;
        }
        else
        {
            friends.push_back(table[i].seatingPos);
        }//adds seating # of friends of 'a' to friends vector

    }
    for (int j = 0; j < 4; j++) {//check friends of 'a' to see if their neighbor is friends with 'b'
        int check2 = table[friends[j]].seatingPos;//check 2 holds seating pos # of 'c'
        if (check2 != 7)
            ++check2;
        else
            return check2;
        if ((table[toSwap].isEnemy(table[check2].getName()))) //if neighbor of c is friends with b(toSwap)
        {
            continue;
        }
        else {
            return check2;//if not enemies then must be friends return seating pos of acceptable candidate

        }
    }

    return 0;
}

当我调试代码时,它说我在分配字符串 nameA = table[checkFriends].getName(); 时遇到未处理的异常;checkfriends = 0 的值,所以它不应该超出向量的范围。

调试器还说:Knights.exe 中 0x7BC8F2F6 (ucrtbased.dll) 处的未处理异常:将无效参数传递给认为无效参数致命的函数。发生这种情况发生在第一个 if 语句期间。谢谢你的帮助!!!

标签: c++exceptionvectorsubscript

解决方案


推荐阅读