繁体   English   中英

如何遍历节点向量

[英]How to iterate through a vector of nodes

我正在实现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的算法函数中,我要遍历邻接表( 此处为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中;

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

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

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

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

我该如何摆脱。

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

typedef struct heap_node HEAP_NODE_STRUCT
vector<HEAP_NODE_STRUCT> 

heap_node struct node

heap_node struct the_heap_node;

因此,您不会隐藏原始节点类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM