c++ - 1455行上的 vector 下标超出范围?

标签 c++ vector

现在正在使用C++进行Udacity类(class),以下代码在其工作区中编译时可以工作,但是当我尝试将其放入CLion并运行时将无法运行。我怀疑Search方法有问题,因为我尝试在计算机上运行上一个练习(尚未填写Search),并且仍然可以正常运行。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout;
using std::ifstream;
using std::istringstream;
using std::string;
using std::vector;
using std::abs;

enum class State {kEmpty, kObstacle, kClosed};


vector<State> ParseLine(string line) {
    istringstream sline(line);
    int n;
    char c;
    vector<State> row;
    while (sline >> n >> c && c == ',') {
        if (n == 0) {
            row.push_back(State::kEmpty);
        } else {
            row.push_back(State::kObstacle);
        }
    }
    return row;
}


vector<vector<State>> ReadBoardFile(string path) {
    ifstream myfile (path);
    vector<vector<State>> board{};
    if (myfile) {
        string line;
        while (getline(myfile, line)) {
            vector<State> row = ParseLine(line);
            board.push_back(row);
        }
    }
    return board;
}


// Calculate the manhattan distance
int Heuristic(int x1, int y1, int x2, int y2) {
    return abs(x2 - x1) + abs(y2 - y1);
}


/**
 * Add a node to the open list and mark it as open.
 */
void AddToOpen(int x, int y, int g, int h, vector<vector<int>> &openlist, vector<vector<State>> &grid) {
    // Add node to open vector, and mark grid cell as closed.
    openlist.push_back(vector<int>{x, y, g, h});
    grid[x][y] = State::kClosed;
}


/**
 * Implementation of A* search algorithm
 */
vector<vector<State>> Search(vector<vector<State>> grid, int init[2], int goal[2]) {
    // Create the vector of open nodes.
    vector<vector<int>> open {};

    // Initialize the starting node.
    int x = init[0];
    int y = init[1];
    int g = 0;
    int h = Heuristic(x, y, goal[0],goal[1]);
    AddToOpen(x, y, g, h, open, grid);

    cout << "No path found!" << "\n";
    return std::vector<vector<State>>{};
}

string CellString(State cell) {
    switch(cell) {
        case State::kObstacle: return "⛰️   ";
        default: return "0   ";
    }
}


void PrintBoard(const vector<vector<State>> board) {
    for (int i = 0; i < board.size(); i++) {
        for (int j = 0; j < board[i].size(); j++) {
            cout << CellString(board[i][j]);
        }
        cout << "\n";
    }
}


int main() {
    int init[2]{0, 0};
    int goal[2]{4, 5};
    auto board = ReadBoardFile("1.board");
    auto solution = Search(board, init, goal);
    PrintBoard(solution);

}```

最佳答案

我想通了,谢谢大家!

由于某种原因,ReadBoardFile调用中的相对路径名不起作用。
求助于绝对文件路径解决了该问题。

关于c++ - 1455行上的 vector 下标超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997572/

相关文章:

c++ - 为什么不能在 C++ 中为动态数组重载插入运算符?

c++ - 重新分配指针时出现段错误

c++ - C++ 计时的纳秒精度

list - 如何将Vector设置为默认实现?

c++ - 这个错误是什么意思? (errorC2678) 以及如何修复我的代码?

c++ - 将字符串数组传递给函数 C++

c++ - 检查 nullptr 100% 是否可以防止有关内存布局的段错误?

c++ - 在模板类中折叠指针?

c++ - 使用集合对 vector 进行排序

c++ - 遍历矩阵的方法