2011-05-13 49 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