c++ - Boost graph:遍历所有顶点并打印相邻顶点
问题描述
我想打印所有顶点及其相邻顶点。我在网上找到了一些关于如何做到这一点的例子,但它对我不起作用。我收到错误消息,即 ++ 运算符不能在 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]
不会编译,因为 avertex_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
推荐阅读
- java - indexOf的重载
- java - 将 oauth 与 Volley 或 Retrofit 一起使用
- powershell - Docker ~ 粘贴到交互式 PowerShell 终端中
- xml - Perl XML:如何在 xml 自闭标签中保留空白?
- c# - Spire.Barcode 从字符串打印条形码
- c# - .Net Core App 初始化 Blob 存储时出现致命错误
- angular - 在 Ubuntu 18.04 上安装 angular-cli 时出现分段错误
- node.js - Oracledb.node 是针对不同的 node.js 版本使用编译的
- java - 通过语音识别搜索数据,而不是在文本框中输入
- kubernetes - 如何在自定义 VPS 上安装 Hasura 平台?