C++提升图 - 为什么我有一个额外的顶点
C++ Boost Graph - Why do I have an additional vertex?
>我有一个图表,其顶点和边缘是自定义类型的。在下面的示例中,我创建了具有 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
从文档中:
如果图形的 VertexList 是 vecS,则图形具有通过 vertex_index_t 属性的属性映射访问的内置顶点索引。指数在 [0, num_vertices(g)) 范围内,并且是连续的。
add_vertex
的描述没有明确说明,但我相信上述内容需要将带有描述符 u 的顶点添加到图形中必须创建顶点 0 到 u(如果它们中的任何一个不存在)。从根本上说,它只是将顶点向量的大小调整为 u + 1,以便 u 成为有效的索引。
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 我的输出中有一个额外的 0,为什么会这样
- 节点是否为空,即使它有一个值?
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- 在 Stream C++ 文本之前有一个额外的换行符
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 如果有一个几何设计着色器,则如何将信息从顶点着色器传递到碎片着色器
- C++提升图 - 为什么我有一个额外的顶点
- C++:图形 ADT 应该有一个顶点列表和一个边列表,或者只是带有指向其他顶点的指针的顶点