【发布时间】:2020-08-31 10:41:45
【问题描述】:
bool isEnemy(const string& check) {
if (check == enemy1 || check == enemy2 ||
check == enemy3) // if the name being checked is an enemy of this knight
return true;
else
return false;
}
int Canidate(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'
for (int i = 0; i < 8; i++) {
if (!(table[i].isEnemy(table[checkFriends].getName()))) // if not enemies,
// then must be
// friends
{
friends.push_back(table[i].seatingPos); // adds seating # of friends of
// 'a' to friends vector
}
}
for (int j = 0; j < 3; 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 (!(table[toSwap].isEnemy(
table[(friends[j] + 1)]
.getName()))) { // if neighbor of c is friends with b(toSwap)
return check2; // if not enemies then must be friends return seating pos
// of acceptable canidate
}
}
}
table 是 vector<Knight>。 friends 是 vector<int>
【问题讨论】:
-
假设你的最后一个 for 循环一直运行而没有返回,那么你的函数返回什么值?
-
你的函数,很明显,如果你的循环没有被输入,或者它们返回的条件从未满足,你的函数不会返回任何东西。
-
在例程结束时,要么执行
return -1;(或任何在您的程序中有意义的标记值),要么执行throw std::runtime_error("never supposed to get here");。 -
明白了,返回-1,解决了不是所有路径都返回值的问题。显然我的函数也使我的向量下标超出范围,我看看我是否能弄清楚为什么会发生这种情况。感谢您抽出宝贵时间
标签: c++ c++11 if-statement vector conditional-statements