Boost图库:获取特定顶点的订单号?

时间:2015-01-29 01:22:39

标签: boost

Boost图形库有一个函数vertex_descriptor vertex(vertices_size_type n, const adjacency_list& g),它返回第n个vertex_descriptor。这个函数的反转是什么?也就是说,要获得给定vertex_descriptor的订单号?

1 个答案:

答案 0 :(得分:1)

一般来说,没有高效的方式,因为它取决于顶点的存储方式。

如果您不关心性能,可以创建如下函数:

template <typename Graph>
size_t index_of(Graph const& g, typename Graph::vertex_descriptor const& vd)
{
    auto vs = vertices(g);
    auto lookup = std::find(vs.first, vs.second, vd);
    assert(lookup != vs.second);

    return std::distance(vs.first, lookup);
}

在&#34;综合&#34;下面的测试显示适用于adjacency_list<>图类型的多种不同配置。

对于vecS存储,上述性能应该合理,但如果不存在,则可能很糟糕。在这种情况下,提供您自己的vertex_index映射会好得多,因为许多其他算法都需要(例如write_graphviz):


测试计划

<强> Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random.hpp>
#include <boost/random.hpp>

using namespace boost;

template <typename Graph>
size_t index_of(Graph const& g, typename Graph::vertex_descriptor const& vd)
{
    auto vs = vertices(g);
    auto lookup = std::find(vs.first, vs.second, vd);
    assert(lookup != vs.second);

    return std::distance(vs.first, lookup);
}

static mt19937 rnd(time(0));

template <typename Graph, size_t num_vertices = 200, size_t num_edges = 300>
void test_index_of()
{
    Graph g;
    generate_random_graph(g, 100, 300, rnd);

    for(auto const& v : make_iterator_range(vertices(g))) {
        assert(v == boost::vertex(index_of(g, v), g));
    }
}

int main()
{
    test_index_of<adjacency_list<vecS,  vecS,  undirectedS> >();
    test_index_of<adjacency_list<vecS,  setS,  undirectedS> >();
    test_index_of<adjacency_list<vecS,  listS, undirectedS> >();
    test_index_of<adjacency_list<setS,  vecS,  undirectedS> >();
    test_index_of<adjacency_list<setS,  setS,  undirectedS> >();
    test_index_of<adjacency_list<setS,  listS, undirectedS> >();
    test_index_of<adjacency_list<listS, vecS,  undirectedS> >();
    test_index_of<adjacency_list<listS, setS,  undirectedS> >();
    test_index_of<adjacency_list<listS, listS, undirectedS> >();
    test_index_of<adjacency_list<vecS,  vecS,  directedS>   >();
    test_index_of<adjacency_list<vecS,  setS,  directedS>   >();
    test_index_of<adjacency_list<vecS,  listS, directedS>   >();
    test_index_of<adjacency_list<setS,  vecS,  directedS>   >();
    test_index_of<adjacency_list<setS,  setS,  directedS>   >();
    test_index_of<adjacency_list<setS,  listS, directedS>   >();
    test_index_of<adjacency_list<listS, vecS,  directedS>   >();
    test_index_of<adjacency_list<listS, setS,  directedS>   >();
    test_index_of<adjacency_list<listS, listS, directedS>   >();
}