【问题标题】:What should function list<Edge> return?函数 list<Edge> 应该返回什么?
【发布时间】:2011-05-13 01:31:25
【问题描述】:

现在我想做的是,对于从 V1 到 V2 的每条边,我想设置 V2 到 V1 的距离(D)。如果 D 小于 V2 的当前距离,那么我们要将 V2 的当前距离设置为 D,并将 V2 的前任设置为 V1。

我已将 V1 声明并初始化为最短距离(这只是初始点),并将其标记为完成。

问题:如何声明 V2 并设置它的距离?

std::list<Edge>* Graph::shortestPath(int fromVertex, int toVertex){
    //initialize distance array set to INFINITY
    //initialize predecceor set to -1
    //initialize  bool done array to false

    std::list<Edge> *listOfEdges = new std::list<Edge>();
    std::list<Edge>::iterator it;
    Edge *edge;

    double *distance = new double [numVertices];
    int *predecessor = new int [numVertices];
    bool *done = new bool [numVertices];

    for(int i =0; i < numVertices; i++){
        distance[i] = INFINITY;
        predecessor[i] = -1;
        done[i] = false;
    }

    distance[fromVertex] = 0;
    predecessor[fromVertex] = UNDEFINED_PREDECESSOR;
    done[fromVertex] = true;


    for(int i =0; i < numVertices; i++){
        if(!done[i] && distance[i] != INFINITY){
            int V1 = getVertexWithSmallestDistanceThatsNotDone(distance, done);//choose smallest distance           
            done[V1] = true;//set vertice to to V1.


            double D = distance[toVertex] + distance[predecessor[toVertex]];
            if(D < distance[toVertex]){
                D = distance[toVertex];
                predecessor[toVertex] = fromVertex;
            }
        }
        return listOfEdges;
    }
}

【问题讨论】:

    标签: list return-value dijkstra shortest-path


    【解决方案1】:

    您正在返回一个指向 std::list 的指针。您通常会在函数中为此结果分配内存

    std::list&lt;Edge&gt; *result = new std::list&lt;Edge&gt;();

    然后,你会返回这个指针

    return result

    在获取此结果的外部函数中,您需要释放动态分配的内存:

    std::list<Edge>* edges = graph.shortestPath(1,5);
    
    //work with edges
    
    delete edges;
    edges = NULL;//good practice to mark it as "not poiting to anything valid"
    

    【讨论】:

    • 谢谢。所以我创建了一个名为边缘的列表并将其返回。我还没有为它设置值,因为我仍然不知道如何将值放入列表中。
    猜你喜欢
    • 2012-12-04
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2020-07-16
    • 2022-01-14
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多