【发布时间】:2018-02-06 19:52:09
【问题描述】:
这与我昨天提出的关于使用整数索引访问顶点的问题有关。该线程在这里:Accessing specific vertices in boost::graph
那里的解决方案表明,使用 vecS 作为顶点的类型,确实可以使用整数索引访问特定的顶点。我想知道 boost 是否提供了类似的方法来使用整数索引有效地访问任意边缘。
附件是描述前者(有效访问具有整数索引的顶点)和访问边的代码,基于开发人员显式维护的两个数组from[] 和to[],分别存储源和目标的边缘。
代码创建以下图表:
#include <boost/config.hpp>
#include <iostream>
#include <fstream>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
using namespace boost;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits;
typedef adjacency_list<
vecS, vecS, directedS,
property<
vertex_name_t, std::string,
property<vertex_index_t, int,
property<vertex_color_t, boost::default_color_type,
property<vertex_distance_t, double,
property<vertex_predecessor_t, Traits::edge_descriptor> > > > >,
property<
edge_index_t, int,
property<edge_capacity_t, double,
property<edge_weight_t, double,
property<edge_residual_capacity_t, double,
property<edge_reverse_t, Traits::edge_descriptor> > > > > >
Graph;
int main() {
int nonodes = 4;
const int maxnoedges = 4;//I want to avoid using this.
Graph g(nonodes);
property_map<Graph, edge_index_t>::type E = get(edge_index, g);
int from[maxnoedges], to[maxnoedges];//I want to avoid using this.
// Create edges
Traits::edge_descriptor ed;
int eindex = 0;
ed = (add_edge(0, 1, g)).first;
from[eindex] = 0; to[eindex] = 1;//I want to avoid using this.
E[ed] = eindex++;
ed = (add_edge(0, 2, g)).first;
from[eindex] = 0; to[eindex] = 2;//I want to avoid using this.
E[ed] = eindex++;
ed = (add_edge(1, 3, g)).first;
from[eindex] = 1; to[eindex] = 3;//I want to avoid using this.
E[ed] = eindex++;
ed = (add_edge(2, 3, g)).first;
from[eindex] = 2; to[eindex] = 3;//I want to avoid using this.
E[ed] = eindex++;
graph_traits < Graph >::out_edge_iterator ei, e_end;
for (int vindex = 0; vindex < num_vertices(g); vindex++) {
printf("Number of outedges for vertex %d is %d\n", vindex, out_degree(vindex, g));
for (tie(ei, e_end) = out_edges(vindex, g); ei != e_end; ++ei)
printf("From %d to %d\n", source(*ei, g), target(*ei, g));
}
printf("Number of edges is %d\n", num_edges(g));
//Is there any efficient method boost provides
//in lieu of having to explicitly maintain from and to arrays
//on part of the developer?
for (int eindex = 0; eindex < num_edges(g); eindex++)
printf("Edge %d is from %d to %d\n", eindex, from[eindex], to[eindex]);
}
代码构建和编译没有错误。带有vindex 的for 循环与out_edges 和out_degree 一起工作正常,将整数索引作为参数。
有没有办法为下一个直接使用 boost::graph 数据结构打印边缘的 for 循环做同样的事情?
我查看了以下处理类似问题的线程:
Boost graph library: Get edge_descriptor or access edge by index of type int
建议的答案是使用unordered_map。与使用 from[] 和 to[] 数组相比,使用它是否有任何权衡?是否有任何其他计算效率高的访问边的方法?
【问题讨论】: