2011-05-13 48 views
0

现在我想要做的是,对于从V1到V2的每个边缘,我想设置V2与V1的距离(D)。如果D小于远离V2的电流,那么我们希望将V2的电流设置为与D相距较远,并将V2的前驱设置为V1。功能列表<Edge>应该返回什么?

我已经声明和初始化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; 
    } 
} 

回答

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" 
+0

谢谢。所以我创建了一个名为边缘的列表并将其返回。我没有为它设置值,因为我仍然不知道如何将值放入列表中。 – Hydride 2011-05-13 02:25:48