如何在有向图上获得给定顶点的输入边?

时间:2016-03-30 15:54:57

标签: c++ c++11 boost-graph

我有一个有向图,我想获取给定顶点的父节点。

假设我有图#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mach/mach.h> #include <mach/vm_map.h> #include <IOKit/IOKitLib.h> int main() { io_service_t service = IOServiceGetMatching(kIOMasterPortDefault, IOserviceMatching("IOUSBHIDDriver")); // change service each time if(!service) { return -1; } io_connect_t connect; kern_return_t kr = IOServiceOpen(service, mach_task_self(), 0, &connect); if(kr != kIOReturnSuccess) { return -1; } uint32_t selector =3; uint64_t input[0]; input[0] = 0x44444444444; IOConnectCallMethod(connect, selector, input, 1, 0, 0, NULL, NULL, NULL, NULL); printf("Did it crash? No? Do it again! -Toxic\n"); } ,我保持顶点1 -> 2 -> 3,我想得到顶点2

我的顶点和图形定义:

1

MVCE显示我想要实现的目标(参见online here):

struct TreeVertex   {  int id = -1;  };

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::directedS,
    TreeVertex
    > tree_t;

Another answer建议将图表转换为int main() { tree_t tree; auto v1 = boost::add_vertex( tree ); auto v2 = boost::add_vertex( tree ); auto v3 = boost::add_vertex( tree ); boost::add_edge( v1, v2, tree ); boost::add_edge( v2, v3, tree ); // attempt to get the input edge of v2 auto pair_it_edge = boost::in_edges( v2, tree ); // FAILS TO BUILD auto v = boost::source( *pair_it_edge.first ); // should be v1 } ,但我需要将其保持定向。

问题:这可能吗?如何获取BidirectionalGraph的传入边缘,以便我可以提取v2

1 个答案:

答案 0 :(得分:2)

如果不使用双向图,则必须对所有节点进行强力搜索,寻找将顶点2作为子节点的节点。

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
using namespace std;
   using namespace boost;

struct TreeVertex   {  int id = -1;  };

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::directedS,
    TreeVertex
    > tree_t;

    tree_t tree;


int main() {


    auto v1 = boost::add_vertex( tree );    
    auto v2 = boost::add_vertex( tree );    
    auto v3 = boost::add_vertex( tree );    
    boost::add_edge( v1, v2, tree );
    boost::add_edge( v2, v3, tree );

    int looking_for = 2;

    typename graph_traits < tree_t >::out_edge_iterator ei, ei_end;
    for( int v = 0; v < num_edges( tree ); v++ )
    for (boost::tie(ei, ei_end) = out_edges(v, tree); ei != ei_end; ++ei) {
    auto source = boost::source ( *ei, tree );
    auto target = boost::target ( *ei, tree );
    if( target == looking_for )
        std::cout << "There is an edge from " << source <<  " to " << target << std::endl;

// create an inverted edge tree to search for parents
tree_t invtree;
boost::add_edge( v2, v1, invtree );
boost::add_edge( v1, v3, invtree );
typename graph_traits < tree_t >::adjacency_iterator it, it_end;
for (tie(it, it_end) = adjacent_vertices(v2, invtree ); it != it_end; ++it) 
{
    std::cout << "There is an inv edge from " <<  v2
        << " to " << *it << std::endl;
}


    return 0;
}

创建一个带有反转边的临时树作为图形的“副本”以简化对父项的搜索可能是值得的。在代码末尾发布了类似于invtree的内容。