将对象添加到boost :: graph

sc_*_*ray 2 c++ boost initialization graph object

我试图创建一个对象图,我需要使用一些遍历算法遍历.在这个时刻,我被困在尝试使用我的自定义对象创建图形.我试图完成它的方式如下:

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <iostream>

using namespace std;
typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::directedS> CustomGraph;
typedef boost::graph_traits<CustomGraph>::vertex_descriptor CustomVertex;

class CustomVisitor:public boost::default_dfs_visitor
{
        public:
                void discover_vertex(CustomVertex v,const CustomGraph& taskGraph) const
                {
                        cerr<<v<<endl;
                        return;
                }


};

class CustomObject{
        private:
                int currentId;
        public:
                CustomObject(int id){
                        currentId = id;
                }

};


int main()
{
        CustomGraph customGraph;
        CustomObject* obj0 = new CustomObject(0);
        CustomObject* obj1 = new CustomObject(1);
        CustomObject* obj2 = new CustomObject(2);
        CustomObject* obj3 = new CustomObject(3);

        typedef std::pair<CustomObject*,CustomObject*> Edge;
        std::vector<Edge> edgeVec;
        edgeVec.push_back(Edge(obj0,obj1));
        edgeVec.push_back(Edge(obj0,obj2));
        edgeVec.push_back(Edge(obj1,obj2));
        edgeVec.push_back(Edge(obj1,obj3));
        customGraph(edgeVec.begin(),edgeVec.end());
        CustomVisitor vis;
        boost::depth_first_search(customGraph,boost::visitor(vis));

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不是在顶点内创建对象的正确方法.有人可以指导我创建节点的正确方法是什么,这样我可以在遍历图形时检索我的对象.

谢谢

小智 8

嗨,我知道这是一个相当古老的问题,但也许其他人可以从答案中受益.

好像你忘了定义你的Graph将自定义类作为顶点.您必须向typedef添加第四个参数,并为您的边添加typedef:

typedef boost::adjacency_list<boost::vecS,boost::vecS,boost::directedS, CustomObject> CustomGraph;
typedef boost::graph_traits<CustomGraph>::vertex_descriptor CustomVertex;
typedef boost::graph_traits<CustomGraph>::edge_descriptor CustomEdge;
Run Code Online (Sandbox Code Playgroud)

然后我通常在连接边缘之前添加我的节点:

// Create graph and custom obj's
CustomGraph customGraph
CustomObject obj0(0);
CustomObject obj1(1);
CustomObject obj2(2);
CustomObject obj3(3);

// Add custom obj's to the graph 
// (Creating boost vertices)
CustomVertex v0 = boost::add_vertex(obj0, customGraph);
CustomVertex v1 = boost::add_vertex(obj1, customGraph);
CustomVertex v2 = boost::add_vertex(obj2, customGraph);
CustomVertex v3 = boost::add_vertex(obj3, customGraph);

// Add edge
CustomEdge edge; 
bool edgeExists;
// check if edge allready exist (only if you don't want parallel edges)
boost::tie(edge, edgeExists) = boost::edge(v0 , v1, customGraph);
if(!edgeExists)
    boost::add_edge(v0 , v1, customGraph);

// write graph to console
cout << "\n-- graphviz output START --" << endl;
boost::write_graphviz(cout, customGraph);
cout << "\n-- graphviz output END --" << endl;
Run Code Online (Sandbox Code Playgroud)