簡體   English   中英

C ++ boost :: graph從有向圖獲取父頂點

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM