使用 Boost Graph [BGL] 检查在 add_edge 之前是不是已经存在顶点
Posted
技术标签:
【中文标题】使用 Boost Graph [BGL] 检查在 add_edge 之前是不是已经存在顶点【英文标题】:Check if vertex already exists before an add_edge using Boost Graph [BGL]使用 Boost Graph [BGL] 检查在 add_edge 之前是否已经存在顶点 【发布时间】:2017-03-30 10:00:38 【问题描述】:有没有办法检查使用 Boost 创建的图中的顶点是否已经存在,而不是循环遍历这些顶点?
如果它已经存在,我如何使用它的顶点描述符添加新边?
例子:
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
【问题讨论】:
vertex.find
是语法错误,什么意思?
【参考方案1】:
我想你可能会喜欢labeled_graph 适配器:
Live On Coliru
#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
【讨论】:
@Avi OT:coliru.stacked-crooked.com/a/e6efd0400c348981(回复您的deleted answer)以上是关于使用 Boost Graph [BGL] 检查在 add_edge 之前是不是已经存在顶点的主要内容,如果未能解决你的问题,请参考以下文章
在 Delphi 7 中使用 C++ Boost 图形库 (BGL)
如何使用 Boost Graph Library 创建 named_graph?