C ++ Boost Graph - 为什么我有一个额外的顶点?

时间:2017-02-02 08:53:03

标签: c++ boost

我有一个顶点和边缘都是自定义类型的图形。在下面的示例中,我创建了包含4个顶点和4个边的图。然而,当我遍历顶点以打印它时,系统总共输出5个顶点。我不确定我做错了什么,我希望有人能够在这方面给我启发。

struct Vertex { int id; double data; };
struct Edge { float distance; };

int main(int, char** argv)
{

typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, Vertex, Edge> Graph;

//instantiate a graph
Graph g;

//add vertices
boost::add_vertex(Vertex{ 1, 1.1 }, g);
boost::add_vertex(Vertex{ 2, 2.2 }, g);
boost::add_vertex(Vertex{ 3, 3.3 }, g);
boost::add_vertex(Vertex{ 4, 4.4 }, g);

boost::add_edge(1, 2, g);
boost::add_edge(1, 4, g);
boost::add_edge(2, 4, g);   
boost::add_edge(1, 3, g);

// Iterate through the vertices and print them out
typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vp;
for (vp = boost::vertices(g); vp.first != vp.second; vp.first++)
    std::cout << g[*(vp.first)].id << " " << g[*(vp.first)].data << std::endl;

// Iterate through the edges and print them out
auto es = boost::edges(g);
for (auto eit = es.first; eit != es.second; ++eit) {
    std::cout << boost::source(*eit, g) << ' ' << boost::target(*eit, g) << std::endl;
}

输出如下

1 1.1
2 2.2
3 3.3
4 4.4
0 0
1 2
1 4
1 3
2 4

1 个答案:

答案 0 :(得分:2)

来自docs

  

如果图形的VertexList是vecS,则图形具有通过vertex_index_t属性的属性映射访问的内置顶点索引。索引落在[0,num_vertices(g))范围内并且是连续的。

add_vertex的描述并没有明确说明,但我相信上述内容必须将带有描述符u的顶点添加到图形中,如果它们中的任何一个没有,则必须创建顶点0到u。已经存在了。从根本上说,它只是将顶点向量的大小调整为大小u + 1,这样你就成了一个有效的索引。