簡體   English   中英

用“純”C ++ 11替代替換BGL迭代頂點?

[英]Replace BGL iterate over vertexes with “pure” C++11 alternative?

我想用純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)] << ") ";
}

我從這里嘗試了幾個建議: 用“純”C ++ 11替換替換BOOST_FOREACH? 但沒有運氣。

我希望能夠寫出如下內容:

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)
{...}

可能嗎?

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);
}

甚至更簡單,一個將std::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))){
  // ...
}

Boost.Graph還提供類似於BOOST_FOREACH便捷宏,但專為Graph迭代而設計。

對給定圖的所有頂點/邊的迭代由宏BGL_FORALL_VERTICES / BGL_FORALL_EDGES及其模板對應物BGL_FORALL_VERTICES_T / BGL_FORALL_EDGES_T

對給定頂點的內邊緣或外邊緣的迭代由宏BGL_FORALL_OUTEDGESBGL_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中都有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM