首页 文章

Boost Graph Library:检查图表是否有定向

提问于
浏览
1

我正在编写一个函数,使用BGL对图形执行一些计算 . 计算的方式取决于图形是否有定向,但我想避免编写两个不同的函数,一个用于无向图,一个用于有向图 . 两种类型的图形定义如下

using namespace boost;
// Undirected
typedef adjacency_list<listS, vecS, undirectedS> UGraph;
// Directed
typedef adjacency_list<listS, vecS, bidirectionalS> DGraph;

有没有办法从图形对象本身检查图形是否定向?换句话说,有没有办法从图形对象中知道所使用的“定向性”属性(即,无向性,双向性或有向性)?

1 回答

  • 0

    我在查看graph_utility.hpp中函数 print_graph() 的定义时找到了答案,这导致我在graph_traits.hpp中定义了函数 is_directed() .

    我想可能有更优雅的方法来做到这一点,但这是一个最小的工作示例:

    #include <iostream>
    #include <boost/graph/adjacency_list.hpp>
    #include <boost/graph/graph_traits.hpp>
    
    
    template <typename graph_t>
    void print_directedness(graph_t &g)
    {
      // Typedef of an object whose constructor returns "directedness" of the graph object.
      typedef typename boost::graph_traits<graph_t>::directed_category Cat;
      // The function boost::detail::is_directed() returns "true" if the graph object is directed.
      if(boost::detail::is_directed(Cat()))
        std::cout << "The graph is directed." << std::endl;
      else
        std::cout << "The graph is undirected." << std::endl;
    }
    
    
    int main()
    {
    
      // Creates an undirected graph and tests whether it is directed of not.
      boost::adjacency_list< boost::setS, boost::vecS, boost::undirectedS > UnGraph;
      print_directedness(UnGraph);
    
      // Creates a directed graph and tests whether it is directed of not.
      boost::adjacency_list< boost::setS, boost::vecS, boost::directedS > DiGraph;
      print_directedness(DiGraph);
    
      // Creates a bidirectional graph and tests whether it is directed of not.
      boost::adjacency_list< boost::setS, boost::vecS, boost::bidirectionalS > BidiGraph;
      print_directedness(BidiGraph);
    
      return 0;
    }
    

    哪个正确返回

    >> g++ minimal_working_example.cpp -o minimal_working_example
    >> ./minimal_working_example
    The graph is undirected.
    The graph is directed.
    The graph is directed.
    

相关问题