我使用 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 edge
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 決定離開這個邊緣,甚至不惜讓它成為回圈。
問題:
- 我該如何解決?
- 如何洗掉頂點的邊緣?
- 在這種情況下使用雙向圖是否更有意義?
另外,我在檔案上找不到任何關于這種行為的內容,所以如果有人能指出我正確的地方,我將不勝感激。
uj5u.com熱心網友回復:
實作不是“遇到麻煩”-它只是在做任何事情,因為您不滿足先決條件:
void remove_vertex(vertex_descriptor u, adjacency_list& g)從圖的頂點集中洗掉頂點 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 edge
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 edge
現在它可以作業了: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";
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444253.html
下一篇:冒泡排序一包卡片
