函数列表<edge>应返回什么?</edge>

时间:2011-05-13 01:31:26

标签: list return-value dijkstra shortest-path

现在我要做的是,对于从V1到V2的每个边缘,我想设置V2的距离(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;
    }
}

1 个答案:

答案 0 :(得分:0)

您正在返回指向std :: list的指针。您通常会在函数

中为此结果分配内存

std::list<Edge> *result = new std::list<Edge>();

然后,你会返回这个指针

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"