Boost::Graph去除重复顶点

1 篇文章 0 订阅

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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值