boost::graph官网:The Boost Graph Library - 1.75.0
named_graph官网:boost/graph/named_graph.hpp - 1.49.0
实际开发中,是将Graph用来节点的内存管理,并且需要节点名称唯一,实现如下:
#include <boost/graph/adjacency_list.hpp>
#include <tuple>
#include <algorithm>
#include <iterator>
#include <iostream>
// 自定义类型MyPath,在内存模型中,需要path唯一
struct MyPath {
std::string path;
std::string name;
int age;
int sex;
};
// 核心!有了这段代码就可以保证节点的唯一!
template<>
struct boost::graph::internal_vertex_name<MyPath> {
struct type {
using result_type = std::string;
const result_type& operator()(const MyPath& data)const {
return data.path;
}
};
};
int main()
{
// 使用adjacency_list,并且连线用set,节点用vec,方向是bidirectional
typedef boost::adjacency_list<boost::setS, boost::vecS, boost::bidirectionalS, MyPath> Graph;
typedef Graph::vertex_descriptor vertex_descriptor;
Graph g;
// 添加根节点
vertex_descriptor root = boost::add_vertex(MyPath{"*", "root", 0, 0}, g);
// 添加子节点1
auto v1 = boost::add_vertex(MyPath{ "*|1", "zhang", 1, 1}, g);
boost::add_edge(root, v1, g);
// 添加子节点2
auto v2 = boost::add_vertex(MyPath{ "*|2", "wang", 2, 2}, g);
boost::add_edge(root, v2, g);
// 添加重复子节点1
auto v3 = boost::add_vertex(MyPath{ "*|1", "zhang", 3, 3}, g);
boost::add_edge(root, v3, g);
Graph::vertex_iterator itor, end;
boost::tie(itor, end) = boost::vertices(g);
std::cout << boost::num_vertices(g) << std::endl;
}
通过path查找descriptor:
const auto& name = g.named_vertices.get<boost::vertex_name_t>();
auto iter = name.find("*|1");
if (iter != name.end()) {
vertex_descriptor d = *iter;
}
通过子节点,查找父节点:
#include <boost/optional/optional_io.hpp>
boost::optional<vertex_descriptor> get_parent_node(const vertex_descriptor& child_node)
{
vertex_descriptor parent_node{};
{
auto iter_range = boost::inv_adjacent_vertices(child_node, g);
auto count = std::distance(iter_range.first, iter_range.second);
if (count == 0) {
return {};
}
if (count != 1) {
return {};
}
parent_node = *iter_range.first;
}
return parent_node;
}