Boost库,如何获取相邻节点?
Posted
技术标签:
【中文标题】Boost库,如何获取相邻节点?【英文标题】:Boost library, how to get neighbouring nodes? 【发布时间】:2018-04-18 11:19:19 【问题描述】:在生成带有n
节点的图并随机添加边之后,我将如何获取特定节点的所有邻居。有没有类似NetworkX的G.neighbors(i)
的功能?
这就是我目前所做的,创建邻接列表
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
using namespace boost;
using namespace std;
int main()
int N = 10000;
struct status_t
typedef vertex_property_tag kind;
;
typedef
property <status_t, string> status;
typedef
adjacency_list<vecS, vecS, undirectedS, status> MyGraph;
MyGraph g (N);
// add some random edges
add_edge(0, 1, g);
add_edge(100, 153, g);
add_edge(634, 12, g);
add_edge(94, 3, g);
property_map<MyGraph, status_t>::type status_map = get(status_t(), g);
for (int i = 0; i < 10; i++)
status_map[i] = "S";
return 0;
【问题讨论】:
漂亮干净的代码。但是请注意,使用自定义属性是不必要的复杂,这些天您可以使用属性包:coliru.stacked-crooked.com/a/134bfbe5805fd0a2 【参考方案1】:auto neighbours = boost::adjacent_vertices(94, g);
像这样打印它们
for (auto vd : make_iterator_range(neighbours))
std::cout << "94 has adjacent vertex " << vd << "\n";
打印
94 has adjacent vertex 93
94 has adjacent vertex 3
如果您只想要传出边缘,则假定 directedS
或 bidirectionalS
,在这种情况下您也可以这样做:
for (auto ed : make_iterator_range(boost::out_edges(94, g)))
std::cout << "outgoing: " << ed << "\n";
for (auto ed : make_iterator_range(boost::in_edges(94, g)))
std::cout << "incident: " << ed << "\n";
现场演示
Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <iostream>
using namespace boost;
using namespace std;
int main()
int N = 10000;
struct status_t typedef vertex_property_tag kind; ;
typedef property<status_t, string> status;
typedef adjacency_list<vecS, vecS, bidirectionalS, status> MyGraph;
MyGraph g(N);
// add some random edges
add_edge(0, 1, g);
add_edge(100, 153, g);
add_edge(634, 12, g);
add_edge(93, 94, g);
add_edge(94, 3, g);
property_map<MyGraph, status_t>::type status_map = get(status_t(), g);
for (int i = 0; i < 10; i++)
status_map[i] = "S";
auto neighbours = boost::adjacent_vertices(94, g);
for (auto vd : make_iterator_range(neighbours))
std::cout << "94 has adjacent vertex " << vd << "\n";
// prints
// for undirected:
// 94 has adjacent vertex 93
// 94 has adjacent vertex 3
// for directed/bidirectionalS:
// 94 has adjacent vertex 3
// for bidirectionalS:
for (auto ed : make_iterator_range(boost::out_edges(94, g)))
std::cout << "outgoing: " << ed << "\n";
for (auto ed : make_iterator_range(boost::in_edges(94, g)))
std::cout << "incident: " << ed << "\n";
打印
94 has adjacent vertex 3
outgoing: (94,3)
incident: (93,94)
【讨论】:
以上是关于Boost库,如何获取相邻节点?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 boost :: 适配器链的 boost 范围获取 std::list
如何从 boost::property_tree 获取枚举?