在抛出' std :: out_of_range'的实例后继续调用终止。

时间:2015-10-17 04:33:28

标签: c++

bool GameUtil::isValidPath(std::vector<int>& path, Player* player, Game* game) {
    ///**Get borad*/
    std::vector<Square*>  board = game->getBoard();
    int maxDistanceTravel = 0;
    int playerCanTravel = 0;
    //first square and last square must be present
    if (path[0] == 0 && path[path.size() - 1] == (board.size() - 1)) {
        for (int i = 0; i < path.size() - 1; i++) {
            /**Max distance of each board from player*/
            maxDistanceTravel = compute(board.at(path[i]), player);
            playerCanTravel = path[i + 1] - path[i];
            if ((playerCanTravel > maxDistanceTravel) && (playerCanTravel <= 0)) {
                return false;
            }
        }
        return true;
    }
    return false;
}

我是一名新的c ++学习者,我一遍又一遍地得到同样的错误,但无法弄清楚它有什么问题,显然不是超出范围,请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我会先尝试做一些早期检查,以确保输入有效。也许是这样的事情:

bool GameUtil::isValidPath(std::vector<int>& path, Player* player, Game* game) {
  assert(!path.empty());
  if (path.size() < 2) return false; // or whatever your minimum size is.

只要你在它,你应该擦洗其他输入。

bool GameUtil::isValidPath(std::vector<int>& path, Player* player, Game* game) {
  assert(!path.empty());
  assert(game);
  assert(player);
  if (path.size() < 2) return false; // or whatever your minimum size is.

我有一个经验法则是使用永远不应为null的参数的引用。在您的代码中看起来不允许游戏为空。所以也许你可以改变这个功能:

bool GameUtil::isValidPath(std::vector<int>& path, Player& player, Game& game) {
  assert(!path.empty());
  if (path.size() < 2) return false; // or whatever your minimum size is.

然后改变你打电话的地方。所以可能在你的代码中你有类似的东西:

// somewhere buried in your code:
Game * myGame = .../// however you created it.
Game * myPlayer = .../// however you created it.
GameUtil * myGameUtil = .../// however you created it.
...
auto isValid = myGameUtil->isValidPath(path, myPlayer, myGame);

您将其更改为:

// somewhere buried in your code:
Game * myGame = .../// however you created it.
Game * myPlayer = .../// however you created it.
GameUtil * myGameUtil = .../// however you created it.
...
auto isValid = myGameUtil->isValidPath(path, *myPlayer, *myGame);

希望有所帮助。