[英]Check if vertex already exists before an add_edge using Boost Graph [BGL]
有沒有辦法檢查使用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
}
我想你可能喜歡labeled_graph適配器:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.