Boost图形库:如何复制图形的节点和边缘而无需复制属性?

8

我正在使用带有捆绑属性的boost图形库。在构建第一棵参考树之后,我想要有几棵具有相同结构和层次结构但具有不同顶点和边属性的树。我发现有一个copy_graph方法,但不知道如何使用它来实现我的目的。

例如,我首先创建了一棵参考树,VertexProperty1EdgeProperty1是捆绑属性。

typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProperty1, EdgeProperty1> Graph;
Graph g1;

一些处理后,g1包含一些顶点和边。 然后我想要一个具有不同绑定属性的复制树。
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, VertexProperty2, EdgeProperty2> Graph2;
copy_graph(g1, g2, ???);

感谢您提前提供任何帮助。最好附上示例代码。
1个回答

10

如果你查看文档,你会发现参数vertex_copyedge_copy实际上是用来复制属性的。这些参数的默认值会复制每个顶点/边上的所有属性,而你需要的是一些什么都不做的东西:

struct do_nothing
{
    template <typename VertexOrEdge1, typename VertexOrEdge2>
    void operator()(const VertexOrEdge1& , VertexOrEdge2& ) const 
    {
    }
};

然后像这样调用copy_graph

copy_graph(g1,g2,boost::vertex_copy(do_nothing()).edge_copy(do_nothing()));

在Coliru上运行

#include <iostream>
#include <string>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/graph_utility.hpp> 

struct VertexProp1
{
    int color;
};

struct VertexProp2
{
    std::string name;
};

struct EdgeProp1
{
    double weight;
};

struct EdgeProp2
{
    std::string name;
};

typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::bidirectionalS,VertexProp1,EdgeProp1> Graph1;
typedef boost::graph_traits<Graph1>::vertex_descriptor VertexDesc;

typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::bidirectionalS,VertexProp2,EdgeProp2> Graph2;

struct do_nothing
{
    template <typename VertexOrEdge1, typename VertexOrEdge2>
    void operator()(const VertexOrEdge1& , VertexOrEdge2& ) const 
    {
    }
};

void build_graph(Graph1& g)
{
    VertexDesc v0=add_vertex(VertexProp1{1},g);
    VertexDesc v1=add_vertex(VertexProp1{2},g);
    VertexDesc v2=add_vertex(VertexProp1{3},g);
    add_edge(v0,v1,EdgeProp1{1.0},g);
    add_edge(v1,v2,EdgeProp1{2.0},g);
    add_edge(v2,v0,EdgeProp1{3.0},g);

}


int main()
{
    Graph1 g1;
    build_graph(g1);

    std::cout << "Graph1" << std::endl;
    print_graph(g1);

    Graph2 g2;

    copy_graph(g1,g2,boost::vertex_copy(do_nothing()).edge_copy(do_nothing()));

    std::cout << "Graph2" << std::endl;
    print_graph(g2);

}

不错,你比我更快地完成了。而且它更好 :) - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接