edge之前是否已经存在顶点

edge之前是否已经存在顶点

本文介绍了使用Boost Graph [BGL]检查add_edge之前是否已经存在顶点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检查使用Boost创建的图形中的顶点是否已经存在,而不是遍历顶点?

Is there a way to check if a vertex in a graph created using Boost already exists rather than looping through the vertices?

如果已经存在,如何使用其顶点描述符添加新边?

And if it already exists, how can I add a new edge using its vertex descriptor?

示例:

Graph g;
vertex v;

v = add_vertex(1, g);
vertex_name[v] = "root";

v = add_vertex(2, g);
vertex_name[v] = "vert_2";

v = add_vertex(3, g);
vertex_name[v] = "vert_3";

// This is not possible
edge e1;
if (vertex.find("root") == vertex.end()) {
   (boost::add_edge("root", "vert_2", g)).first
}

推荐答案

我认为您可能喜欢labeled_graph适配器:

I think you may like the labeled_graph adaptor:

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/labeled_graph.hpp>

using namespace boost;

int main()
{
    using AdjList = adjacency_list<setS, vecS, directedS>;
    using Graph = labeled_graph<AdjList, std::string, hash_mapS>;

    Graph g;

    for (std::string name : { "root", "vert_2", "vert_3" }) {
        add_vertex(name, g);
    }

    struct { std::string from, to; } edges [] = {
        {"root", "vert_2"},
        {"vert_2", "vert_3"},
        {"vert_2", "vert_3"},
        {"vert_2", "new_1"},
        {"new_1", "new_2"},
    };

    for (auto const& addition : edges) {
        if (g.vertex(addition.from) == g.null_vertex())
            std::cout << "source vertex (" << addition.from << ") not present\n";
        else if (g.vertex(addition.to) == g.null_vertex())
            std::cout << "target vertex (" << addition.to << ") not present\n";
        else {
            auto insertion = add_edge_by_label(addition.from, addition.to, g);
            std::cout << "Edge: (" << addition.from << " -> " << addition.to << ") "
                << (insertion.second? "inserted":"already exists")
                << "\n";
        }
    }
}

打印:

Edge: (root -> vert_2) inserted
Edge: (vert_2 -> vert_3) inserted
Edge: (vert_2 -> vert_3) already exists
target vertex (new_1) not present
source vertex (new_1) not present

这篇关于使用Boost Graph [BGL]检查add_edge之前是否已经存在顶点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:59