提升图:遍历所有顶点并打印相邻顶点
Boost graph: Iterating through all vertices and printing adjacent vertices
我想打印所有顶点及其相邻顶点。我在网上找到了一些关于如何做到这一点的例子,但它对我不起作用。我收到错误,++运算符不能在ai上使用。另外,我认为它需要vertex_idMap[*ai]
而不是vertex_idMap[ai]
,但这会提示错误。有谁知道为什么这是错误的?
typedef adjacency_list<vecS, listS, directedS, VertexIDPorperty, EdgeWeight> Graph; //the type of g
graph_traits <Graph>::vertex_iterator i, end;
graph_traits <Graph>::adjacency_iterator ai, a_end;
for (boost::tie(i, end) = vertices(g); i != end; ++i) {
std::cout << vertex_idMap[*i];
for (; ai != a_end; ++ai) { //the ++ai seems to be wrong?
std::cout << vertex_idMap[ai];
if (boost::next(ai) != a_end)
std::cout << ", ";
}
std::cout << std::endl;
观察结果:
- 其余代码在哪里?这显然取决于所使用的类型。
ai
和a_end
没有初始化(也许你实际上并不意味着代码无法编译,这是你的全部问题)vertex_idMap[ai]
不会编译,因为vertex_iterator
不是有效的vertex_descriptor
下面是一个固定的示例,其中设想了缺失的位:
住在科里鲁
#include <boost/graph/adjacency_list.hpp>
#include <iostream>
using VertexIDPorperty = boost::property<boost::vertex_index_t, int>;
using EdgeWeight = boost::property<boost::edge_weight_t, double>;
typedef boost::adjacency_list<boost::vecS, boost::listS, boost::directedS, VertexIDPorperty, EdgeWeight> Graph;
Graph sample();
int main() {
Graph g = sample();
auto vertex_idMap = get(boost::vertex_index, g);
boost::graph_traits <Graph>::vertex_iterator i, end;
boost::graph_traits <Graph>::adjacency_iterator ai, a_end;
for (boost::tie(i, end) = vertices(g); i != end; ++i) {
std::cout << vertex_idMap[*i] << ": ";
for (boost::tie(ai, a_end) = adjacent_vertices(*i, g); ai != a_end; ++ai) {
std::cout << vertex_idMap[*ai];
if (boost::next(ai) != a_end)
std::cout << ", ";
}
std::cout << std::endl;
}
}
实现sample()
以创建随机图:
#include <boost/graph/random.hpp>
#include <random>
Graph sample() {
Graph g;
std::mt19937 prng { std::random_device{}() };
generate_random_graph(g, 10, 20, prng);
int id = 0;
for (auto vd : boost::make_iterator_range(vertices(g))) {
put(boost::vertex_index, g, vd, ++id);
}
return g;
}
它打印类似以下内容:
1: 9, 9, 4
2: 6
3:
4:
5: 9, 9, 8, 9
6: 9, 3, 1
7: 2, 10
8: 6
9: 8
10: 7, 3, 8, 1, 4
开箱即用
打印图表可以更简单:
#include <boost/graph/graph_utility.hpp>
// ...
int main() {
print_graph(sample());
}
住在科里鲁
1 -->
2 --> 3 10 9 6 6 10
3 --> 8
4 -->
5 --> 4
6 --> 1 5 8
7 --> 4 9 2 2 1
8 --> 6
9 --> 5 7
10 --> 7
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 提升图:遍历所有顶点并打印相邻顶点
- 使用Vertex_descriptor boost图在顶点上打印或迭代
- 似乎无法使用<VERTEX>迭代器在 for 循环中打印列表顶点?C++
- 打印带有自定义顶点标签的助推图
- 如何打印图中两个顶点之间的最短路径?
- 按CGAL顶点打印排列_2