簡體   English   中英

在無向圖中通過頂點查找邊 [C++ BGL]

[英]Find an Edge by its vertices in an undirected graph [C++ BGL]

我的問題很簡單。 鑒於它連接的頂點,我正在尋找一條邊。 復雜的方法是遍歷所有邊並將每個源和目標與我使用的頂點進行比較。 我認為必須有更好的方法來做到這一點,這就是我問的原因

這取決於您的圖形模型: https : //valelab4.ucsf.edu/svn/3rdpartypublic/boost/libs/graph/doc/graph_concepts.html

AdjacencyMatrix 有你想要的直接:

 auto e = boost::edge(v, u, graph);

(其中 e、v 和 u 是描述符)。

假設你有一個 AdjacencyList 的非雙向實例,你將不得不查看源頂點的鄰接:

using Graph = boost::adjacency_list<>;
using V     = Graph::vertex_descriptor;
using E     = Graph::edge_descriptor;

E my_find_edge(V v, V u, Graph const& g)
{
    for (auto e : boost::make_iterator_range(out_edges(v, g))) {
        if (target(e, g) == u)
            return e;
    }
    throw std::domain_error("my_find_edge: not found");
}

在雙向圖的情況下,您可以選擇從目標頂點出發。


演示

實時編譯器資源管理器

#include "boost/graph/adjacency_list.hpp"
#include <boost/range/iterator_range.hpp>

using Graph = boost::adjacency_list<>;
using V     = Graph::vertex_descriptor;
using E     = Graph::edge_descriptor;

E my_find_edge(V v, V u, Graph const& g)
{
    for (auto e : boost::make_iterator_range(out_edges(v, g))) {
        if (target(e, g) == u)
            return e;
    }
    throw std::domain_error("my_find_edge: not found");
}

#include "boost/graph/random.hpp"
#include <random>
int main() {
    std::mt19937 prng { std::random_device{}() };

    for (auto i = 0; i < 10; ++i)
        try {
            Graph g;
            generate_random_graph(g, 10, 20, prng);

            E e = my_find_edge(7, 2, g);
            std::cout << "Found: " << e << "\n";
        } catch (std::exception const& e) {
            std::cout << e.what() << "\n";
        }
}

打印例如

my_find_edge: not found
my_find_edge: not found
Found: (7,2)
Found: (7,2)
my_find_edge: not found
my_find_edge: not found
my_find_edge: not found
my_find_edge: not found
my_find_edge: not found
Found: (7,2)

進一步優化

setS頂點選​​擇器的情況下,您可能能夠使用std::binary_search和朋友( std::lower_boundstd::upper_boundstd::equal_range )進行優化。

我會大量咨詢我的分析器,看看這是否真的提高了性能。 我有一種感覺,除非你的出度非常高,否則可能不會。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM