10

我想用纯 C++11 等价物替换顶点或边上的 BGL 迭代。BGL 代码(来自: http: //www.boost.org/doc/libs/1_52_0/libs/graph/doc/quick_tour.html)是:

typename boost::graph_traits<Graph>::out_edge_iterator out_i, out_end;
typename boost::graph_traits<Graph>::edge_descriptor e;
for (std::tie(out_i, out_end) = out_edges(v, g);
     out_i != out_end; ++out_i)
{
  e = *out_i;
  Vertex src = source(e, g), targ = target(e, g);
  std::cout << "(" << name[get(vertex_id, src)]
            << "," << name[get(vertex_id, targ)] << ") ";
}

我从这里尝试了几个建议:Replace BOOST_FOREACH with "pure" C++11 alternative? 但没有运气。

我希望能够写出类似的东西:

for (auto &e : out_edges(v, g))
{ ... }

或类似的东西:

for (std::tie(auto out_i, auto out_end) = out_edges(v, g);
     out_i != out_end; ++out_i)
{...}

是否可以?

4

2 回答 2

9

一个简单的包装out_edges就足够了:

#include <boost/range/iterator_range.hpp>
#include <type_traits>

template<class T> using Invoke = typename T::type
template<class T> using RemoveRef = Invoke<std::remove_reference<T>>;
template<class G> using OutEdgeIterator = typename boost::graph_traits<G>::out_edge_iterator;

template<class V, class G>
auto out_edges_range(V&& v, G&& g)
  -> boost::iterator_range<OutEdgeIterator<RemoveRef<G>>>
{
  auto edge_pair = out_edges(std::forward<V>(v), std::forward<G>(g));
  return boost::make_iterator_range(edge_pair.first, edge_pair.second);
}

或者更简单,将 astd::pair转换为有效范围的函数:

template<class It>
boost::iterator_range<It> pair_range(std::pair<It, It> const& p){
  return boost::make_iterator_range(p.first, p.second);
}

进而

for(auto e : pair_range(out_edges(v, g))){
  // ...
}
于 2012-11-19T12:24:09.340 回答
3

Boost.Graph 还提供了类似于BOOST_FOREACH但专门为 Graph 迭代设计的便利宏。

对给定图的所有顶点/边的迭代由宏BGL_FORALL_VERTICES/BGL_FORALL_EDGES及其模板对应物BGL_FORALL_VERTICES_T/提供BGL_FORALL_EDGES_T

对给定顶点的内边或外边的迭代由宏BGL_FORALL_OUTEDGES或提供BGL_FORALL_INEDGES。(为他们的模板版本添加 _T)。对于邻接顶点,使用BGL_FORALL_ADJ.

例子:

#include <boost/graph/iteration_macros.hpp>

typedef ... Graph;
Graph g;
BGL_FORALL_VERTICES(v, g, Graph)  //v is declared here and 
{                                   //is of type Graph::vertex_descriptor
     BGL_FORALL_OUTEDGES(v, e, g, Graph)  //e is declared as Graph::edge_descriptor
     {

     }
}

这些宏在 C++03 和 C++11 中都有效。

于 2013-11-17T22:27:48.673 回答