[英]boost::graph: How to remove in-edges of a previously removed vertex?
我使用 boost::graph 創建了最簡單的有向圖,並添加了 2 個通過 2 條邊相互連接的頂點。
刪除第一個頂點后,第二個頂點仍然有一個指向先前刪除的頂點的出邊。
boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::directedS,
boost::no_property,
boost::no_property
> graph;
// add 2 vertices and connect them
auto v0 = boost::add_vertex(graph);
auto v1 = boost::add_vertex(graph);
boost::add_edge(v0, v1, graph);
boost::add_edge(v1, v0, graph);
// remove the first vertex
boost::remove_vertex(v0, graph);
// iterate over vertices and print their out_degree.
auto [begin, end] = boost::vertices(graph);
for (auto vertex_itr = begin; vertex_itr != end; ++vertex_itr)
{
auto vertex_descriptor = *vertex_itr;
auto out_degree = boost::out_degree(vertex_descriptor, graph);
std::cout << out_degree << '\n'; // this prints 1
}
據我了解,我的圖處於一種“無效狀態”,其中一條邊指向一個不存在的頂點。 通過進一步檢查,似乎“懸掛邊緣”已成為source == target
的邊緣。 這讓我更加困惑為什么 boost::graph 決定留下這條邊,甚至 go 來讓它循環。
問題:
此外,我在文檔中找不到任何關於此行為的信息,所以如果有人能指出我正確的位置,我將不勝感激。
實現不是“經歷麻煩”——它只是在做任何事情,因為你不滿足先決條件:
void remove_vertex(vertex_descriptor u, adjacency_list& g)
從圖的頂點集中刪除頂點 u。 假設當頂點 u 被移除時,沒有邊到達或來自頂點 u。 確保這一點的一種方法是事先調用
clear_vertex()
。
我稍微簡單地重述了你的問題: Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <iostream>
int main() {
boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> g(2);
add_edge(0, 1, g);
add_edge(1, 0, g);
print_graph(g, std::cout << "--- Before: ");
remove_vertex(0, g); // remove the first vertex
print_graph(g, std::cout << "--- After: ");
// iterate over vertices and print their out_degree.
for (auto [it, end] = boost::vertices(g); it != end; ++it)
std::cout << out_degree(*it, g) << "\n"; // this prints 1
}
印刷
--- Before: 0 --> 1
1 --> 0
--- After: 0 --> 0
1
讓我們簡單地按照文檔所說的那樣做:
clear_vertex(0, g); // clear edges
remove_vertex(0, g); // remove the first vertex
現在可以使用了: Live On Coliru ,打印:
--- Before: 0 --> 1
1 --> 0
--- After: 0 -->
0
為了更優雅:
// iterate over vertices and print their out_degree.
for (auto v : boost::make_iterator_range(vertices(g)))
std::cout << v << " out_degree: " << out_degree(v, g) << "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.