[英]C++ Boost Graph - Why do I have an additional vertex?
I have a graph whose vertex and edge are of custom type. 我有一个顶点和边为自定义类型的图。 In my example below, I created the graph with 4 vertices and 4 edges.
在下面的示例中,我创建了具有4个顶点和4条边的图形。 When I iterate through the vertices to print it however, the system outputs a total of 5 vertices.
但是,当我遍历顶点进行打印时,系统总共输出5个顶点。 I am unsure what I did wrong and I hope someone would be able to enlighten me on this.
我不确定自己做错了什么,希望有人能对此有所启发。
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;
}
the output are as follows 输出如下
1 1.1
2 2.2
3 3.3
4 4.4
0 0
1 2
1 4
1 3
2 4
If the VertexList of the graph is vecS, then the graph has a builtin vertex indices accessed via the property map for the vertex_index_t property.
如果图形的VertexList是vecS,则该图形具有内置的顶点索引,可通过属性映射访问vertex_index_t属性。 The indices fall in the range [0, num_vertices(g)) and are contiguous.
索引落在[0,num_vertices(g))范围内,并且是连续的。
The description of add_vertex
doesn't say it explicitly, but I believe that the above necessitates that adding vertex with descriptor u into a graph must create vertices 0 through u if any of them don't already exist. add_vertex
的描述没有明确说明,但我认为上述要求必须将带有描述符u的顶点添加到图中必须创建顶点0到u(如果其中不存在)。 Fundamentally, it just resizes the vertex vector to the size u + 1, so that u becomes a valid index. 从根本上讲,它只是将顶点矢量的大小调整为u + 1,以便u成为有效索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.