c++ - 如何在 boost 图中添加彩色边?

标签 c++ boost boost-graph

   int main()
   {
   using namespace std;
   using namespace boost;
   typedef adjacency_list< listS, vecS, directedS > digraph;

   // instantiate a digraph object with 8 vertices
   digraph g;


   // add some edges
   add_edge(0, 1, g);
   add_edge(1, 5, g);
   add_edge(5, 6, g);``
   add_edge(2, 3, g);
   add_edge(2, 4, g);

   // represent graph in DOT format and send to cout
   write_graphviz(cout, g);
   return 0;
   }       

请告诉我如何添加彩色边而不是彩色顶点。 例如顶点 0 和 1 之间的边我希望它给它一些颜色例如红色 所以所有其他边应该是不同的颜色,顶点 0 和 1 之间的边应该是红色,我该如何设置该属性。

最佳答案

您可以使用 property writer 来做到这一点.

按照这些思路可以完成这项工作:

#include <iostream>
#include <boost/graph/graphviz.hpp>

using namespace std;

  using namespace boost;

  typedef adjacency_list< listS, vecS, directedS > digraph;

    //  define a property writer to color the edges as required
  class color_writer {
  public:

      // constructor - needs reference to graph we are coloring
    color_writer( digraph& g ) : myGraph( g ) {}

      // functor that does the coloring
    template <class VertexOrEdge>
    void operator()(std::ostream& out, const VertexOrEdge& e) const {

        // check if this is the edge we want to color red
        if( source( e, myGraph ) == 0 &&
            target( e, myGraph ) == 1  )
                out << "[color=red]";
    }
  private:
    digraph& myGraph;
  };

int main()
{
   using namespace std;

   // instantiate a digraph object with 8 vertices
   digraph g;

   // add some edges
   add_edge(0, 1, g);
   add_edge(1, 5, g);
   add_edge(5, 6, g);
   add_edge(2, 3, g);
   add_edge(2, 4, g);


   // represent graph in DOT format and send to cout 
   write_graphviz(cout, g,
        default_writer(),       // default ( do nothing ) vertex property writer
        color_writer( g ) );    // edge color property writer
   return 0;
}

运行这个产生

digraph G {
0;
1;
2;
3;
4;
5;
6;
0->1 [color=red];
1->5 ;
2->3 ;
2->4 ;
5->6 ;
}

当输入点程序时给出:

enter image description here

关于c++ - 如何在 boost 图中添加彩色边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25082053/

相关文章:

c++ - 在 C++ 中覆盖文件(不追加)

c++ - strcpy_s 是 C++ 标准的一部分吗?或者只是 MS Visual C++ 的一部分

python - 从哪里获得 boost/python.hpp?

c++ - boost 图形库 : access violation in reading from adjacency_list in parallel mode

c++ - boost 中有一个 DAG 图,没有顶点描述符失效

c++ - enable_if 的奇怪行为

c++ - 程序忽略第二个循环

c++ - 使用 Boost::interprocess 在共享内存中映射 <int, void*>

c++ - boost 原子类使初始化值不同于成员初始化列表

c++ - 减少邻接表的内存需求