如何遍历节点向量

时间:2015-06-03 06:52:42

标签: c++ vector graph dijkstra shortest-path

我正在实施Dijkstra的最短路径算法。我按如下方式创建了一个节点类:

node::node(int to,int weight)
{
    this->to = to;
    this->weight = weight;
}

我创建了一个图表类:

class Graph
{
    int V,E;
    vector<node> *adj;
    public :
        Graph(int V,int E);
        void addEdge(int v,int w,int weight);
        void dijkstra(int src,int V);
};

Graph::Graph(int V,int E)
{
    this->V = V;
    this->E = E;
}

void Graph::addEdge(int v,int w,int weight)
{
    node x(w,weight);
    adj[v].push_back(x);
    node y(v,weight);
    adj[w].push_back(y);
}

现在在Dijkstra的算法函数中,我想迭代邻接列表( here vector ):

void Graph::dijkstra(int src,int V)
{
    struct heap_node node[V];
    for(int i=0;i<V;i++)
    {
        node[i].vertex_value = INT_MAX;
        node[i].vertex_no = i;
    }
    bool visited[V];
    memset(visited,false,sizeof(visited));
    node[src].vertex_value = 0;
    make_heap(node,node+V,compare);
    //As we have set vertex_value(distance from source) of the source node to 0,We are left with V-1 vertices. So, we will run a for loop. 
    for(int i=0;i<V-1;i++)  
    {
        pop_heap(node,node-i-1,compare);
        //This will extract the minimum from the heap and set it to the last position. 
        int cur = V-i-1;
        int u = node[cur].vertex_no;
        visited[u] = true;
        vector<node>::iterator it;
        for(it = adj[u].begin() ; it != adj[u].end() ; it++)
        {
            node v = *it;
        }
    }
}

但它给了我以下错误:

dijkstra1.cpp:在成员函数'void Graph :: dijkstra(int,int)'中: dijkstra1.cpp:79:10:错误:'node'不能出现在常量表达式中    vector :: iterator it;

dijkstra1.cpp:79:14:错误:模板参数1无效    vector :: iterator it;

dijkstra1.cpp:79:14:错误:模板参数2无效

dijkstra1.cpp:79:26:错误:'it'之前的预期初始化程序    vector :: iterator it;

dijkstra1.cpp:80:7:错误:'it'未在此范围内声明    for(it = adj [u] .begin(); it!= adj [u] .end(); it ++)

我如何摆脱它。

1 个答案:

答案 0 :(得分:1)

看起来有两种类型:heap_node和节点类。 我不确定哪种类型是adj,但无论哪种方式,都不能使向量类型成为实例。它必须是一种类型。所以要么成功

typedef struct heap_node HEAP_NODE_STRUCT
vector<HEAP_NODE_STRUCT> 

或c 绞死了 heap_node struct node  到

heap_node struct the_heap_node;

所以你不要隐藏原始节点类。