提升图了解顶点创建行为

时间:2014-09-09 07:37:46

标签: c++ boost graph

我试图弄清楚使用add_edge函数时顶点创建的行为。这是一个例子:

#include <iostream> 
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>

using namespace boost;
typedef adjacency_list<> Graph;
typedef graph_traits<Graph>::vertex_iterator v_iter;

Graph g;
add_edge(1,2,g);
add_edge(1,4,g);
add_edge(2,3,g);
add_edge(2,6,g);

    std::cout << "num edges: " << num_edges(g) << "; num vertices: " << num_vertices(g) << std::endl;
for (std::pair<v_iter,v_iter> vp = vertices(g);  vp.first != vp.second; vp.first++) {
    std::cout << *vp.first << " ";
}

返回:

bash-3.2$ ./main
num edges: 4; num vertices: 7
0 1 2 3 4 5 6 

为什么要创建这些顶点?该图有1,2,3,4和6作为顶点,总共5个不是7.看起来该函数创建了从0​​到顶点最高值的顶点。

我真的不知道这里发生了什么,所以非常感谢任何帮助。

非常感谢你。

3 个答案:

答案 0 :(得分:3)

邻接列表存储每个顶点的相邻节点:

enter image description here

根据文档:

  

VertexList容器的选择器,用于表示图形的顶点列表   默认值: vecS

这意味着索引到向量是顶点ID。你不能有一个包含索引1但没有索引0的向量。因此,你可以“免费”获得所有中间索引。

当然,你可以调整一下:使用例如顶点列表的listS:看到它 Live On Coliru

#include <iostream> 
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <algorithm>

using namespace boost;
typedef adjacency_list<boost::listS> Graph;
typedef graph_traits<Graph>::vertex_iterator v_iter;

int main()
{
    Graph g;

    graph_traits<Graph>::vertex_descriptor v[] = {
        {}, // unused
        add_vertex(g), add_vertex(g), add_vertex(g),
        add_vertex(g), add_vertex(g), add_vertex(g),
    };

    add_edge(v[1], v[2], g);
    add_edge(v[1], v[4], g);
    add_edge(v[2], v[3], g);
    add_edge(v[2], v[6], g);

    std::cout << "num edges: " << num_edges(g) << "; num vertices: " << num_vertices(g) << std::endl;
    for (std::pair<v_iter, v_iter> vp = vertices(g); vp.first != vp.second; ++vp.first) {
        std::cout << std::distance(v, std::find(std::begin(v), std::end(v), *vp.first)) << " ";
    }
}

打印

num edges: 4; num vertices: 6
1 2 3 4 5 6 Press any key to continue . . .

答案 1 :(得分:0)

刚想通了:这些值被视为索引。例如:

add_edge(1,200); 

假设实际上有200个顶点并将第二个与201顶点连接起来。显然,它们之间的所有顶点都是自动创建的。

了Bw

答案 2 :(得分:0)

它会创建与最高数字一样多的顶点,这意味着,当您编写

add_edge(60)

你将有61个从0开始的顶点