Boost DFS如何保存访问过的顶点

Boost DFS how to save visited vertices?

本文关键字:访问 顶点 保存 DFS 何保存 Boost      更新时间:2023-10-16

我正在查看这里的解决方案,它对我不起作用(但请阅读===行下面的内容以实际查看当前问题)。

我试着:

boost::undirected_dfs(G, vertex(0,G), boost::visitor(vis)); 

但是我得到

error C2780: 'void boost::undirected_dfs(const Graph &,const boost::bgl_named_params<P,T,R> &)' : expects 2 arguments - 3 provided
error C2780: 'void boost::undirected_dfs(const Graph &,DFSVisitor,VertexColorMap,EdgeColorMap)' : expects 4 arguments - 3 provided

等。我有点明白问题是什么了(我需要传递一些命名参数,但我的图中没有。而且,我完全不明白彩色地图是怎么回事。

=============================================================================

我的图是定义的:

typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, EdgeInfoProperty > Graph;
typedef Graph::edge_descriptor Edge;
typedef Graph::vertex_descriptor Vertex;

我只想做DFS,至少现在是这样。

所以我把它改为boost::depth_first_search,它似乎工作。

我有(注意void discover_vertex与上面链接的解决方案相比缺乏const):

class MyVisitor : public boost::default_dfs_visitor {
public:
    void discover_vertex(Vertex v, const Graph& g)  { //note the lack of const
        if(boost::in_degree(v,g)!=0){ //only print the vertices in the connected component (I already did MCC and removed edges so all the extra vertices are isolated)
            std::cerr << v << std::endl;
            vv.push_back(v);
        }
        return;
    }
    std::vector<Vertex> GetVector() const  { return vv; }
private: 
    std::vector<Vertex> vv;
};

如果我把const留在那里,我会得到error C2663: 'std::vector<_Ty>::push_back' : 2 overloads have no legal conversion for 'this' pointer with [ _Ty=size_t ]

现在,这工作得很好,至少它打印出正确访问的顶点,以正确的顺序:

MyVisitor vis;
boost::depth_first_search(G, boost::visitor(vis)); 

但是当我这样做的时候:

std::vector<Vertex> vctr = vis.GetVector();
std::cout<<vctr.size();

的大小是零,因为我的vv没有改变…

那么,当类被用作boost::visitor的参数时,我如何获得适当的类行为?(我甚至不确定这是不是一个合适的问题)。我需要能够根据之前访问的节点来更改EdgeInfoProperty(或者更确切地说,根据哪个顶点是DFS遍历中当前顶点的父顶点,所以这可能只是朝着那个方向迈出的第一步)。

visitor是按值传递的,因此需要与复制到函数调用中的MyVisitor实例共享它所保存的vector。

试试这个:

class MyVisitor : public boost::default_dfs_visitor {
public:
    MyVisitor(): vv(new std::vector<Vertex>()){}
    void discover_vertex(Vertex v, const Graph& g)  { //note the lack of const
        if(boost::in_degree(v,g)!=0){ //only print the vertices in the connected component (I already did MCC and removed edges so all the extra vertices are isolated)
            std::cerr << v << std::endl;
            vv->push_back(v);
        }
        return;
    }
    std::vector<Vertex>& GetVector() const  { return *vv; }
private: 
    boost::shared_ptr< std::vector<Vertex> > vv;
};