[英]c++ boost::graph get parent vertices from directed graph
我有一个有向图(通过boost :: graph库中的adjacency_graph实现),我试图找到某个顶点的父顶点。
在过去(通过pygraph)我简单地颠倒了有向图,然后进行了邻居搜索,但似乎用boost :: reverse_graph反转图形会将我的有向图变成双向图,因此我不能使用adjacent_vertices方法了。
有没有更好的方法来获取父顶点?
谢谢。
这是我当前的示例代码:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <iostream>
typedef boost::adjacency_list< boost::setS, boost::vecS, boost::directedS > Graph;
typedef boost::reverse_graph<Graph> Rgraph;
typedef Graph::vertex_descriptor Vertex;
int main()
{
Graph graph;
Vertex v0 = boost::add_vertex(graph);
Vertex v1 = boost::add_vertex(graph);
Vertex v2 = boost::add_vertex(graph);
Vertex v3 = boost::add_vertex(graph);
Vertex v4 = boost::add_vertex(graph);
Vertex v5 = boost::add_vertex(graph);
Vertex v6 = boost::add_vertex(graph);
boost::add_edge(v0,v1,graph);
boost::add_edge(v1,v2,graph);
boost::add_edge(v2,v3,graph);
boost::add_edge(v2,v4,graph);
boost::add_edge(v3,v5,graph);
boost::add_edge(v4,v5,graph);
boost::add_edge(v5,v6,graph);
Graph::adjacency_iterator ibegin, iend;
for (boost::tie(ibegin, iend) = boost::adjacent_vertices(v2, graph); ibegin != iend; ++ibegin)
{
std::cout << *ibegin << std::endl;
}
std::cout << std::endl << "############# RGRAPH #############" << std::endl << std::endl;
Rgraph rgraph(graph);
Rgraph::adjacency_iterator rbegin, rend;
for (boost::tie(rbegin, rend) = boost::adjacent_vertices(v2, rgraph); rbegin != rend; ++rbegin)
{
std::cout << *rbegin << std::endl;
}
std::cout << std::endl;
return 0;
}
reverse_graph
要求适应的图形是BidirectionalGraph
的模型。 如果您将图形更改为typedef boost::adjacency_list< boost::setS, boost::vecS, boost::bidirectionalS > Graph;
您的程序编译并给出结果:
3
4
############# RGRAPH #############
1
我相信这是您应该期望的。
另一种不需要reverse_graph
(但仍需要bidirectionalS
)的方法是使用:
Graph::out_edge_iterator out_begin, out_end;
for (boost::tie(out_begin, out_end) = out_edges(v2,graph); out_begin != out_end; ++out_begin)
{
std::cout << target(*out_begin,graph) << std::endl;
}
std::cout << std::endl;
Graph::in_edge_iterator in_begin, in_end;
for (boost::tie(in_begin, in_end) = in_edges(v2,graph); in_begin != in_end; ++in_begin)
{
std::cout << source(*in_begin,graph) << std::endl;
}
std::cout << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.