【问题标题】:Printing the names of vertices in topological order with the Boost Graph Library使用 Boost Graph Library 按拓扑顺序打印顶点名称
【发布时间】:2011-03-25 12:05:40
【问题描述】:

我正在尝试使用 Boost 图形库。我想为我的图打印出拓扑排序。但是,我想要在图表上的输出是顶点的实际名称,而不是数字位置。例如,在以下示例中:

typedef boost::adjacency_list<vecS, vecS, directedS,
                              property<vertex_name_t, std::string>,
                              property<edge_weight_t, int> > Graph;

typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
typedef std::vector< Vertex > container;
Graph g;
BOOST_CHECK(read_graphviz(in, g, dp, "id"));
container c;
topological_sort(g, std::back_inserter(c));

std::cout << "A topological ordering: ";
for ( container::reverse_iterator ii=c.rbegin(); ii!=c.rend(); ++ii)
    std::cout <<*ii<<" ";                                               
std:: cout <<std::endl;

我得到以下输出:

A topological ordering: 45 40 41 34 35 33 43 30 31 36 32 26 27 25 23 24 19 46 47 18 48 17 20 21 49 50 16 51 15 44 14 22 42 13 37 38 9 11 28 29 12 7 39 6 8 5 10 3 4 0 2 1 

这些值是有序顶点的位置,但我宁愿知道每个顶点的名称。有人知道怎么做吗?

【问题讨论】:

    标签: c++ boost graph


    【解决方案1】:

    嗯,这个通用编程让我很困惑 :) 试试这个代码。至少它应该可以编译!

    std::cout << get(vertex_name, g, *ii) << " ";
    

    【讨论】:

      【解决方案2】:

      我一直觉得在使用 BGL 时使用自定义节点/边缘类更容易:

      struct Node {
          int x;
          int y;
          std::string name;
      };
      
      struct Edge {
          int weight;
      };
      
      //boost:: qualifiers removed for brevity
      typedef adjacency_list<vecS, vecS, directedS, Node, Edge> Graph;
      
      ...
      {
          Graph g;
          Graph::vertex_descriptor v = ...;
      
          g[v].x = 1;
          std::cout << g[v].name << std::endl;
      }
      

      但是是的,因为*ii 是一个顶点描述符,您应该能够按照@Tom Sirgedas 提到的方式使用它。 (谁在我写我的时候发布了他的答案)

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        相关资源
        最近更新 更多