c++ - labels_graph 上的广度优先搜索

标签 c++ boost-graph

假设以下设置,应该如何使用labeled_graph调用breadth_first_search? - 导致 2 个错误:

二进制“[”:找不到采用“Vertex”类型右侧操作数的运算符(或者没有可接受的转换)

“.id”左侧的错误 2 必须具有类/结构/union

#include<iostream>
#include<boost/graph/adjacency_list.hpp>
#include<boost/graph/breadth_first_search.hpp>
#include <boost/graph/labeled_graph.hpp>

using namespace boost;

struct NodeInfo{int id;};
struct EdgeInfo{};

typedef boost::labeled_graph< boost::adjacency_list<
    boost::vecS, boost::vecS, boost::undirectedS, NodeInfo, EdgeInfo>,
    std::string> Graph;

typedef boost::graph_traits<Graph>::vertex_descriptor GridVertex;

class Topology 
{
public:

    Graph grid;
    std::map<std::string, GridVertex> vertices; //_id to Edge

    struct custom_visitor : public boost::default_bfs_visitor
    {
        Graph& grid;

        custom_visitor(Graph& grid) :grid(grid)  {}

        template <typename Vertex, typename Graph>
        void discover_vertex(Vertex v, const Graph& g)
        {

            //vertex(...) in breadth_first_search is causing: 
            //binary '[' : no operator found which takes a right-hand operand of 
            //type 'Vertex' (or there is no acceptable conversion)  
            //left of .id must have class...
            int m = grid[v].id;

        }
    };

    void GetShortestPath(std::string s_id, std::string t_id)
    {
        custom_visitor vis(grid);

        //vertex(...) causes error
        breadth_first_search(grid.graph(), vertex(vertices[s_id],grid.graph()), visitor(vis));
    }

    void BuildNet()
    {
        Graph g;
        GridVertex v;

        v = add_vertex("A", NodeInfo(), g);
        vertices["A"] = v;

        v = add_vertex("B", NodeInfo(), g);
        vertices["B"] = v;

        add_edge_by_label("A", "B", EdgeInfo(), g);
    }
};


int main()
{
    Topology net;
    net.GetShortestPath("A", "B");
    return 0;
}

最佳答案

为什么使用labeled_graph?

带标签的图具有与只是 adjacency_list 不同的接口(interface)。这并不奇怪,否则还有什么意义:)

因此,如果 vertex(...) 导致错误,请使用 grid.vertex(s_id):

breadth_first_search(grid.graph(), grid.vertex(s_id), visitor(vis));

在访问者中,使用实际的图表,以便您可以使用其运算符[]:

int m = grid.graph()[v].id;

或者,事实上为什么不使用为此目的而存在的第二个参数:

void discover_vertex(Vertex v, const Graph& g) {
    int m = g[v].id;
}

努力从代码中创建一个合理的示例: Live On Coliru

关于c++ - labels_graph 上的广度优先搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35880930/

相关文章:

c++ - 如果顶点属性是指针,如何使用 boost::graph dijkstra 算法?

c++ - 使用继承函数转换 bug

c++ - 自定义 vector 类型

c++ - 将命名参数和捆绑属性与 edmonds_karp_max_flow() 结合使用

c++ - boost 图列表或 vec

c++ - BGL 通过键索引顶点

c++ - 有没有办法在 Visual C++ 调试后返回以前的状态?

c++ - 如何绘制变暗的QPixmap?

c++ - 提取 "invokables"的签名

boost-graph - LEDA 图 v/s Boost 图库