将数据从结构加载到该结构的向量中时出现问题

Issues loading data from a struct into a vector of that struct

本文关键字:结构 向量 问题 数据 加载      更新时间:2023-10-16

该结构仅在我的类的一个函数中。我一直在调试并尝试我能想到的一切。这是针对图形的,该函数用于Dijkstra公式。我遇到的主要问题是我的数据永远不会进入我的向量(向量打开)。

不确定是否需要所有代码,因为所有问题都发生在此函数中。当前未使用的代码(尝试先将数据放入向量)已被注释掉。

void Graph::Dijkstra(string start, string end, vector<string> &path)
{
    struct node
    {
        string name;
        vector<string> connection;
        int costSoFar;
        node() {name = " "; costSoFar = 0;}
        node(node& other)
        {
            name = other.name;
            connection = other.connection;
            costSoFar = other.costSoFar;
        }
    };
    vector<string> adjacent;
    node startNode;
    node current;
    node endNode;
    vector<node> open;
    node closed[MAX_VERTICES];
    int small, temp;
    bool found = false;
    bool inClosed = false;
    bool inOpen = false;
    string tempVertex;
    // starting node is added open list
    // startNode = node();
    startNode.name = start;
    startNode.costSoFar = 0;
    //adjacent.push_back(startNode.name);
    open.push_back(startNode);
    temp = 0; // used a place holder for debugging
    //open[0].name = startNode.name; 
    //open[0].costSoFar = startNode.costSoFar;
}

任何帮助将不胜感激。我看过类似的帖子并尝试了他们的建议,不确定为什么即使我尝试直接应用它,我的向量也不会接受输入(请参阅上面的注释代码)。

我相信 std 容器需要表单的复制构造函数:

node(const node& other);

这是默认复制构造函数的形式(如果未提供)。如果确实提供了复制构造函数,则不会为您提供此默认构造函数,因此您必须定义该表单之一。

好的,

我找到了自己的解决方案。如果结构是在函数内部创建的,则它无法以所需的方式访问变量。我所做的只是将节点结构移动到函数的外部。

struct node
{
    string name;
    vector<string> connection;
    int costSoFar;
    node() {name = " "; costSoFar = 0;}
    node(const node& other)
    {
        name = other.name;
        connection = other.connection;
        costSoFar = other.costSoFar;
    }
};
void Graph::Dijkstra(string start, string end, vector<string> &path)
{ // the other code needed }