vendredi 27 janvier 2017

Understanding segmentation faults in references when popping from queue

I've got the following function:

std::vector<Node> BFS(Graph g, Node source, Node target) {
    std::queue<std::vector<Node> > q;
    std::vector<Node> path = {source};
    q.push(path);
    while (!q.empty()) {
        std::vector<Node> cur_path = q.front();
        q.pop();
        Node cur_node = cur_path[cur_path.size() - 1];
        if (cur_node.data == target.data) {
            return cur_path;
        }
        // for (int i = 0; i < g.edge_map[cur_path].size(); i++) {
        //     std::vector<Node> new_path = cur_path;
        //     new_path.push_back(g.edge_map[cur_path][i]);
        //     q.push(new_path);
        // }
    }
}

Now, I'm not claiming this accomplishes a search at the moment, I just want to know why it causes a segmentation fault. I know it's because I've got that q.pop(); bit, but why? Is this because vectors are inherently references? I can include more of my code if needed, just trying to encapsulate the issue at hand.

Aucun commentaire:

Enregistrer un commentaire