[转]Boost Graph Library

5.  C++ Boost graph库 广度优先遍历算法示例

https://blog.csdn.net/RobinKin/article/details/301865

2005年02月25日 15:43:00 robinkin 阅读数:2981

//(整理by RobinKin  from DevonIT)
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/pending/indirect_cmp.hpp>
#include <boost/pending/integer_range.hpp>

#include <iostream>

using namespace boost;
template < typename TimeMap > class bfs_time_visitor:public default_bfs_visitor {
  typedef typename property_traits < TimeMap >::value_type T;
public:
  bfs_time_visitor(TimeMap tmap, T & t):m_timemap(tmap), m_time(t) { }
  template < typename Vertex, typename Graph >
    void discover_vertex(Vertex u, const Graph & g) const
  {
    put(m_timemap, u, m_time++);//每次访问 m_time加1 
  }
  TimeMap m_timemap;
  T & m_time;
};


int
main()
{
  using namespace boost;
  // Select the graph type we wish to use
  typedef adjacency_list < vecS, vecS, undirectedS > graph_t;
  // Set up the vertex IDs and names
  enum { r, s, t, u, v, w, x, y, N };
  const char *name = "rstuvwxy";
  // Specify the edges in the graph
  typedef std::pair < int, int >E;  //边对
  E edge_array[] = { E(r, s), E(r, v), E(s, w), E(w, r), E(w, t),
    E(w, x), E(x, t), E(t, u), E(x, y), E(u, y)
  };
  // Create the graph object
  const int n_edges = sizeof(edge_array) / sizeof(E);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
  // VC++ has trouble with the edge iterator constructor
  graph_t g(N);
  for (std::size_t j = 0; j < n_edges; ++j)
    add_edge(edge_array[j].first, edge_array[j].second, g);
#else
  typedef graph_traits<graph_t>::vertices_size_type v_size_t;
  graph_t g(edge_array, edge_array + n_edges, v_size_t(N));//构造图
#endif

  // Typedefs
  typedef graph_traits < graph_t >::vertex_descriptor Vertex;
  typedef graph_traits < graph_t >::vertices_size_type Size;
  typedef Size* Iiter;

  // a vector to hold the discover time property for each vertex
  std::vector < Size > dtime(num_vertices(g));//访问时间

  Size time = 0;
  bfs_time_visitor < Size * >vis(&dtime[0], time);
  breadth_first_search(g, vertex(s, g), visitor(vis));

  // Use std::sort to order the vertices by their discover time
  std::vector<graph_traits<graph_t>::vertices_size_type > discover_order(N);
  integer_range < int >range(0, N);
  std::copy(range.begin(), range.end(), discover_order.begin());
  std::sort(discover_order.begin(), discover_order.end(),
            indirect_cmp < Iiter, std::less < Size > >(&dtime[0]));

  std::cout << "order of discovery: ";
  for (int i = 0; i < N; ++i)
    std::cout << name[discover_order[i]] << " ";
  std::cout << std::endl;

  return EXIT_SUCCESS;
}

// 输出  :
order of discovery: s r w v t x u y

 

 

4. https://stackoverflow.com/questions/671714/modifying-vertex-properties-in-a-boostgraph

E:\Program Files\boost\boost_1_61_0\libs\graph\example\kevin-bacon2.cpp

vertex and edge properties can be stored in regular structs or classes.

//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, 
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/config.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/tuple/tuple.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <map>
#include <boost/graph/adj_list_serialize.hpp>
#include <boost/archive/text_iarchive.hpp>

struct vertex_properties {
  std::string name;

  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & name;
  }  
};

struct edge_properties {
  std::string name;

  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & name;
  }  
};

using namespace boost;

typedef adjacency_list<vecS, vecS, undirectedS, 
               vertex_properties, edge_properties> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef graph_traits<Graph>::edge_descriptor Edge;

class bacon_number_recorder : public default_bfs_visitor
{
public:
  bacon_number_recorder(int* dist) : d(dist) { }

  void tree_edge(Edge e, const Graph& g) const {
    Vertex u = source(e, g), v = target(e, g);
    d[v] = d[u] + 1;
  }
private:
  int* d;
};

int main()
{
  std::ifstream ifs("./kevin-bacon2.dat");
  if (!ifs) {
    std::cerr << "No ./kevin-bacon2.dat file" << std::endl;
    return EXIT_FAILURE;
  }
  archive::text_iarchive ia(ifs);
  Graph g;
  ia >> g;

  std::vector<int> bacon_number(num_vertices(g));

  // Get the vertex for Kevin Bacon
  Vertex src;
  graph_traits<Graph>::vertex_iterator i, end;
  for (boost::tie(i, end) = vertices(g); i != end; ++i)
    if (g[*i].name == "Kevin Bacon")
      src = *i;

  // Set Kevin's number to zero
  bacon_number[src] = 0;

  // Perform a breadth first search to compute everyone' Bacon number.
  breadth_first_search(g, src,
                       visitor(bacon_number_recorder(&bacon_number[0])));

  for (boost::tie(i, end) = vertices(g); i != end; ++i)
    std::cout << g[*i].name << " has a Bacon number of "
          << bacon_number[*i] << std::endl;

  return 0;
}
 

3. Graph Setup: Internal Properties

from 《The Boost Graph Library: User Guide and Reference Manual》

http://www.informit.com/articles/article.aspx?p=25756&seqNum=7

 

 

2. 访问属性,并查找最短路径

https://blog.csdn.net/HETONGDE/article/details/79421075

boost graph lib 下建图,并绑定属性,然后查找最短路径

2018年03月02日 11:11:32 河桐 阅读数:306

#include <iostream>

#include <vector>

#include <boost/config.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/graph_utility.hpp>

// Create a struct to hold properties for each vertex
typedef struct vertex_properties
{
  std::string label;
  int p1;
} vertex_properties_t;


// Create a struct to hold properties for each edge
typedef struct edge_properties
{
  std::string label;
  //int   p1;
  double   weight;
} edge_properties_t;


// Define the type of the graph
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, vertex_properties_t, edge_properties_t> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_descriptor_t;
typedef graph_t::edge_descriptor   edge_descriptor_t;
typedef boost::property_map<graph_t, boost::vertex_index_t>::type index_map_t;
typedef boost::iterator_property_map<vertex_descriptor_t*, index_map_t*, vertex_descriptor_t, vertex_descriptor_t&> predecessor_map_t;

//  The graph, with edge weights labeled.
//
//   v1  --(1)--  v2
//   |  \_        |
//   |    \       |
//  (1)    (3)   (2)
//   |        \_  |
//   |          \ |
//   v4  --(1)--  v3
//
//

int main(int,char*[])
{
  // Create a graph object
  graph_t g;

  // Add vertices
  vertex_descriptor_t v1 = boost::add_vertex(g);
  vertex_descriptor_t v2 = boost::add_vertex(g);

  //vertex_descriptor_t v11 = boost::add_vertex(g);
  //vertex_descriptor_t v22 = boost::add_vertex(g);

  vertex_descriptor_t v3 = boost::add_vertex(g);
  vertex_descriptor_t v4 = boost::add_vertex(g);

   vertex_descriptor_t v5 = boost::add_vertex(g);

  // Set vertex properties
  g[v1].p1 = 1;  g[v1].label = "v1";
  g[v2].p1 = 2;  g[v2].label = "v2";

  //g[v11].p1 = 2;  g[v11].label = "v11";
  //g[v22].p1 = 1;  g[v22].label = "v22";

  g[v3].p1 = 3;  g[v3].label = "v3";
  g[v4].p1 = 4;  g[v4].label = "v4";

  g[v5].p1 = 5;  g[v5].label = "v5";

  // Add edges
  std::pair<edge_descriptor_t, bool> e012 = boost::add_edge(v1, v2, g);
  std::pair<edge_descriptor_t, bool> e021 = boost::add_edge(v2, v1, g);

  std::pair<edge_descriptor_t, bool> e023 = boost::add_edge(v2, v3, g);
  std::pair<edge_descriptor_t, bool> e034 = boost::add_edge(v3, v4, g);
  std::pair<edge_descriptor_t, bool> e041 = boost::add_edge(v4, v1, g);
  std::pair<edge_descriptor_t, bool> e013 = boost::add_edge(v1, v3, g);

  std::pair<edge_descriptor_t, bool> e025 = boost::add_edge(v2, v5, g);

  // Set edge properties
//  g[e01.first].p1 = 1;
//  g[e02.first].p1 = 2;
//  g[e03.first].p1 = 3;
//  g[e04.first].p1 = 4;
//  g[e05.first].p1 = 5;

  g[e012.first].weight = 1;
  g[e021.first].weight = 1;

  g[e023.first].weight = 2;
  g[e034.first].weight = 3;
  g[e041.first].weight = 5;
  g[e013.first].weight = 6;

  g[e025.first].weight = 7;

  g[e012.first].label = "v1-v2";
  g[e021.first].label = "v2-v1";
  g[e023.first].label = "v2-v3";
  g[e034.first].label = "v3-v4";
  g[e041.first].label = "v4-v1";
  g[e013.first].label = "v1-v3";

  // Print out some useful information
  std::cout << "Graph:" << std::endl;
  boost::print_graph(g, boost::get(&vertex_properties_t::p1,g));
  std::cout << "num_verts: " << boost::num_vertices(g) << std::endl;
  std::cout << "num_edges: " << boost::num_edges(g) << std::endl;


  // BGL Dijkstra's Shortest Paths here...
  std::vector<double> distances( boost::num_vertices(g));
  std::vector<vertex_descriptor_t> predecessors(boost::num_vertices(g));

  //Vertex s = *(vertices(G).first);
 //       // invoke variant 2 of Dijkstra's algorithm
 //       dijkstra_shortest_paths(G, s, distance_map(&d[1]));

 //       std::cout << "distances from start vertex:" << std::endl;
 //       graph_traits<Graph>::vertex_iterator vi;
 //       for(vi = vertices(G).first; vi != vertices(G).second; ++vi)
 //           std::cout << "distance(" << index[*vi] << ") = "
 //           << d[*vi] << std::endl;
 //       std::cout << std::endl;
  vertex_descriptor_t vSource;
  vertex_descriptor_t vtarget;
  boost::graph_traits<graph_t>::vertex_iterator vi;
  bool bFindSource = false;
  bool bFindTarget = false;
  for(vi = boost::vertices(g).first; vi != boost::vertices(g).second; ++vi)
  {
       if(g[*vi].p1 == 4)
       {
           vSource = *vi;
           bFindSource = true;
       }
       if(g[*vi].p1 == 5)
       {
           vtarget = *vi;
           bFindTarget = true;
       }

       if(bFindSource && bFindTarget)
       {
           break;
       }
       else
       {
           return 0;
       }
  }

  boost::dijkstra_shortest_paths(g, vSource,
                                 boost::weight_map(boost::get(&edge_properties_t::weight,g))
                                 .distance_map(boost::make_iterator_property_map(distances.begin(), boost::get(boost::vertex_index,g)))
                                 .predecessor_map(boost::make_iterator_property_map(predecessors.begin(), boost::get(boost::vertex_index,g)))
                                 );

  // Extract the shortest path from v1 to v3.
  typedef std::vector<edge_descriptor_t> path_t;
  path_t path;

  vertex_descriptor_t v = vtarget;
  for(vertex_descriptor_t u = predecessors[v]; u != v; v=u, u=predecessors[v])
  {
    std::pair<edge_descriptor_t,bool> edge_pair = boost::edge(u,v,g);
    path.push_back( edge_pair.first );
  }

  std::cout << std::endl;
  //std::cout << "Shortest Path from v1 to v3:" << std::endl;
  //std::cout << "distance v1 to v3:" <<distances[3]<<std::endl;
  double distance = 0;
  for(path_t::reverse_iterator riter = path.rbegin(); riter != path.rend(); ++riter)
  {
    vertex_descriptor_t u_tmp = boost::source(*riter, g);
    vertex_descriptor_t v_tmp = boost::target(*riter, g);
    edge_descriptor_t   e_tmp = boost::edge(u_tmp, v_tmp, g).first;
    distance += g[e_tmp].weight;
    std::cout << "  " << g[u_tmp].p1 << " -> " << g[v_tmp].p1 << "    (weight: " << g[e_tmp].weight << ")" << std::endl;
  }
  std::cout << "distance v1 to v3:" <<distance<<std::endl;
  return 0;
}

 

 

1. 快速入门

这是翻译的boost graph的quick tour。

https://blog.csdn.net/u011630575/article/details/80837629

 

 

Boost Graph Library 快速入门

     图领域的数据结构和算法在某些方面比容器更为复杂,图算法在图中移动有着众多的路线,而STL使用的抽象迭代器接口不能有效的支持这些。作为替换,我们为图提供了一个的抽象的结构,其与容器迭代器的目的类似(尽管迭代器扮演着更大的角色)。图1 描述了STL 和BGL 之间的对比。

               图1: The analogy between the STL and the BGL.

       


    图由一系列顶点vertices,以及连接顶点的边edges组成. 如图2描述了一个拥有5个顶点和11条边的有向图directed graph. 离开一个顶的边称为该点的out-edges。边 {(0,1),(0,2),(0,3),(0,4)} 都是节点0的out-edges ,进入一个顶点的边称为该点的in-edges , 边{(0,4),(2,4),(3,4)} 是节点0的in-edges  
 

                  图2 一个有向图例子

                     

 

在后面的章节中,我们使用BGL构造上图并展示各种操作。全部的代码可以在examples/quick_tour.cpp  中找到,下面每个章节都是这个例子文件的一个片断。

构造一个图

     在这个例子中,我们将使用BGL邻接表adjacency_list 类来示范BGL接口中的主要概念。adjacency_list类提供了典型邻接表数据结构的一个泛型版本。 adjacency_list 是一个拥有6个模板参数的模板类。但我们只使用了前3个参数,剩余的3个使用默认参数。头两个模板参数(vecS, vecS)分别用来描述离开顶点的out-edges边图中顶点的集合所使用的数据结构(阅读 Choosing the Edgelist and VertexList 章节可以获得更多关于平衡不同数据结构的信息)。 第三个参数, 使用bidirectionalS表示选择一个可访问出、入边的有向图,其中directedS 为选择一个仅提供出边的有向图;undirectedS 表示选择一个无向图。

    一旦我们选定了图的类型,我们可以创建一个图2所示的图。声明一个图对象,使用 MutableGraph 接口中的add_edge() 函数来填充边,在这个例子中我们简单的使用 pairs 数组edge_array来建立边在这个例子中我们简单的使用 pairs 数组edge_array来建立边。

 
  1. #include <iostream> // for std::cout

  2. #include <utility> // for std::pair

  3. #include <algorithm> // for std::for_each

  4. #include <boost/graph/graph_traits.hpp>

  5. #include <boost/graph/adjacency_list.hpp>

  6. #include <boost/graph/dijkstra_shortest_paths.hpp>

  7. using namespace boost;

  8.  
  9. int main(int,char*[])

  10. {

  11. typedef adjacency_list<vecS, vecS, bidirectionalS> Graph;

  12. // Make convenient labels for the vertices

  13. enum { A, B, C, D, E, N }; //代表 0 ,1,2,3,4 顶点,其中N为顶点数

  14. const int num_vertices = N;//N的值是5

  15. const char* name = "ABCDE";

  16. //图中的边

  17. typedef std::pair<int, int> Edge;

  18. Edge edge_array[] = { Edge(A,B), Edge(A,D), Edge(C,A), Edge(D,C),

  19. Edge(C,E), Edge(B,D), Edge(D,E) };

  20. const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]);

  21. // 创建一个拥有5个顶点的图对象

  22. Graph g(num_vertices);

  23. // 给图对象添加边

  24. for (int i = 0; i < num_edges; ++i)

  25. add_edge(edge_array[i].first, edge_array[i].second, g);//其中first表示第一个顶点,second表示第二个顶点,两个顶点连接

  26. return 0;

  27. }

 

    我们可以使用图的edge iterator constructor 构造函数来代替为每个边调用add_edge()函数,这种方法

更具代表性比add_edge()更有效率,edge_array 指针可以被视为迭代器,所以我们可以传递数组开始和结束的指针给图构造函数

Graph g(edge_array, edge_array + sizeof(edge_array) / sizeof(Edge), num_vertices);

其中edge_array是边集合。同样可以使用 MutableGraph 接口的add_vertex()和remove_vertex() 来为图添加和删除顶点,

而不是一开始就创建一个拥有一定数目顶点的图。

访问顶点集合

    现在我们创建了一个图,我们可以使用图接口访问图数据,首先我们可以通过VertexListGraph 接口的vertices() 函数来访问图中所有的顶点。这个函数返回一个顶点迭代器的std::pair 类型(第一个迭代器指向顶点的开始,第二个迭代器指向顶点的结束)。提领一个顶点迭代器放回一个顶点对象。顶点迭代器的类型可由graph_traits 类取得,值得注意的是不同的图类型可能有不同的顶点迭代器类型,这也是为什么我们需要graph_traits 类的原因。给定一个图类型,graph_traits类能提供该图的vertex_iterator类型,下面的例子打印了图中每个顶点的索引。所有的顶点和边属性,以及索引,可以通过property_map 对象访问。property_map 类可用来获得指定属性(通过指定BGL预定义的vertex_index_t来取得索引)的property_map 类型,通过调用函数get(vertex_index, g) 来获得图当前的property_map对象。

 

 
  1. int main(int,char*[])

  2. {

  3. ......//省略上面代码

  4. //获得顶点索引的 property map

  5. typedef property_map<Graph, vertex_index_t>::type IndexMap;

  6. IndexMap index = get(vertex_index, g);

  7.  
  8. std::cout << "vertices(g) = ";

  9. typedef graph_traits<Graph>::vertex_iterator vertex_iter;

  10. std::pair<vertex_iter, vertex_iter> vp;

  11. for (vp = vertices(g); vp.first != vp.second; ++vp.first)

  12. std::cout << index[*vp.first] << " ";

  13. std::cout << std::endl;

  14.  
  15. return 0;

  16. }

输出结果: 
vertices(g) = 0 1 2 3 4

访问边集合

   一个图的边集合可以使用EdgeListGraph接口中的 edges()函数访问。与vertices() 函数类似,这个函数也返回一对迭代器,但在这里的迭代器是边迭代器edge iterators提领边迭代器可以获得一个边对象,调用source()和target()函数可以取得边连接的两个顶点。这次我们使用tie()辅助函数,而不是为迭代器声明一个pair类型,这个便利的函数可以用来分开std::pair 到两个分离的变量,这里是ei 和 ei_end,这样比创建一个std::pair 类型方便。这也是我们为BGL选择的方法。

 

 
  1. int main(int,char*[])

  2. {

  3. .......//省略上文代码

  4. //获得顶点索引的 property map

  5. typedef property_map<Graph, vertex_index_t>::type IndexMap;

  6. IndexMap index = get(vertex_index, g);

  7.  
  8. std::cout << "edges(g) = ";

  9. graph_traits<Graph>::edge_iterator ei, ei_end;

  10. for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)

  11. std::cout << "(" << index[source(*ei, g)]<< "," << index[target(*ei, g)] << ") ";

  12. std::cout << std::endl;

  13.  
  14. return 0;

  15. }

输出结果:
edges(g) = (0,1) (0,2) (0,3) (0,4) (2,0) (2,4) (3,0)(3,1) (3,4) (4,0) (4,1)

邻接结构

     在下面的例子中我们通过观察一个特殊的顶点来展示图的邻接结构,我们将看到顶点的 in-edges, out-edges 以及他的邻接点adjacent vertices。我们将这些封装到一个"exercise vertex" 函数对象,并针对图的每个顶点调用它。为了示范BGL同STL协作的能力, 我们使用STL的for_each() 函数迭代每个顶点并调用此函数。
int main(int,char*[])
{
    std::for_each(vertices(g).first, vertices(g).second, exercise_vertex<Graph>(g));
    return 0;
}
     当我们访问每个顶点的信息时需要使用到图对象,所以我们把exercise_vertex写成一个函数对象而不是函数,在std::for_each()执行期间,使用函数对象可以给我们提供了一个位置来保持对图对象的引。为了能够处理不同的图对象,我们将此函数对象模板化。这里是exercise_vertex 函数对象的开始
template <class Graph> struct exercise_vertex 
{
    exercise_vertex(Graph& g_) : g(g_) {}
    Graph& g;
};

顶点描述符

   在撰写函数对象operator()方法时,我们首先要知道的是图中顶点对象的类型。顶点类型用来声明operator()中的参数。确切的说,我们实际上并不处理顶点对象,而是使用顶点描述符vertex_descriptors。许多图结构(如邻接表adjacency lists)并不需要存储顶点对象,而另一些存储(例如 pointer-linked graphs),这些不同将被顶点描述符对象的黑箱操作所隐藏。顶点描述符由图类型提供,在后面章节将介绍通过对操作符调用函数out_edges(), in_edges(), adjacent_vertices()和property_map来访问图信息。顶点描述符类型可以通过graph_traits类获得,下面语句中的typename 关键字是必须的,因为在范围操作符::左边(graph_traits<Graph>类型)由模板参数(Graph类型)确定。下面是我们定义的函数对象
template <class Graph> struct exercise_vertex
{
    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
    void operator()(const Vertex& v) const
    {
    }
};

Out-Edges, In-Edges, 和Edge 描述符

    可以通过IncidenceGraph接口中的out_edges()函数来访问一个顶点的out-edges, 这个函数需要两个参数:第一个参数是顶点,第二个是图对象。函数返回一对迭代器,来提供对一个顶点所有out-edges的访问(与vertices()函数返回pair对象类似)。这些迭代器称为out-edge iterators, 提领这些迭代器将返回一个边描述符对象,边描述符跟顶点描述符扮演类似性质的角色,也是图类型提供的黑盒,后面的代码片断按source-target顺序打印了顶点v对应的每个out-edge边上的两个点。
template <class Graph> struct exercise_vertex 
{
    void operator()(const Vertex& v) const
    {
         //...... 
        typedef graph_traits<Graph> GraphTraits;
        typename property_map<Graph, vertex_index_t>::type 
        index = get(vertex_index, g);

        std::cout << "out-edges: ";
        typename GraphTraits::out_edge_iterator out_i, out_end;
        typename GraphTraits::edge_descriptor e;
        for (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 << "(" << index[src] << "," << index[targ] << ") ";
        }
        std::cout << std::endl;
    }
};
对于顶点0 输出结果是: 
out-edges: (0,1) (0,2) (0,3) (0,4)

     in_edges()  函数位于BidirectionalGraph接口中,此函数可以通过in-edge迭代器访问一个顶点所有的in-edges。 只有当邻接表的Directed(第三个)模板参数设为bidirectionalS 才能使用此函数。而指定bidirectionalS代替directedS时将会花费更多的空间。
template <class Graph> struct exercise_vertex 
{
    void operator()(const Vertex& v) const
    {
        //....... 省略与上面重复代码
        std::cout << "in-edges: ";
        typedef typename graph_traits<Graph> GraphTraits;
        typename GraphTraits::in_edge_iterator in_i, in_end;
        for (tie(in_i, in_end) = in_edges(v,g); in_i != in_end; ++in_i) 
        {
            e = *in_i;
            Vertex src = source(e, g), targ = target(e, g);
            std::cout << "(" << index[src] << "," << index[targ] << ") ";
        }
        std::cout << std::endl;
    }
};
对于顶点 0 输出是: 
in-edges: (2,0) (3,0) (4,0)

邻接点

   当给出一个顶点的所有的out-edges边时,这些边上的目标点对于源点邻接。有时一个算法不需要关注一个图的边,而是仅关心顶点。因此图形接口AdjacencyGraph 提供了adjacent_vertices()函数来直接访问邻接点。此函数返回一对adjacency iterators ,提领一个邻接点迭代器将会得到领接顶点的顶点描述符。
template <class Graph> struct exercise_vertex 
{
    void operator()(Vertex v) const
    {
        //.......
        std::cout << "adjacent vertices: ";
        typename graph_traits<Graph>::adjacency_iterator ai;
        typename graph_traits<Graph>::adjacency_iterator ai_end;
        for (tie(ai, ai_end) = adjacent_vertices(v, g);ai != ai_end; ++ai)
               std::cout << index[*ai] << " ";
        std::cout << std::endl;
    }
};

给你的图添加一些颜色

   BGL实现尽可能灵活地适应图的附加属性,举个例子,属性如边的权重存在于在图对象的整个生命周期都,因此让图对象管理这个属性的存储将会带来很多便利;另外,属性如顶点颜色只在某个算法的运行期内需要,将此属性和图对象分开存储将会更好。第一种属性称为内在存储属性,而第二种称为外在存储属性。BGL 在图算法中为两种属性提供了一致的访问接口property_map,此接口在章节Property Map Concepts中有详细描述。另外,PropertyGraph 配接器也为获得一个内在存储属性的property map 对象定义了接口

    BGL 邻接表类允许用户通过设置图对象模版参数来指定内在存储属性,如何实现这些在Internal Properties 章节有详细论述。外在存储属性有多种创建方法,尽管他们基本上作为分离参数传递给图算法。一个简单存储外在属性的办法是通过顶点或边的索引来创建一个索引数组。如邻接表中的VertexList模版参数指定为vecS,每个顶点的索引将会自动建立。通过指定vertex_index_t作为模版参数的property map对象来访问这些索引。每个边虽不能自动建立索引。但是可以通过使用属性机制把索引和边联系起来,来索引其他的外在存储属性。

   在下面的例子中,我们创建一个图并执行dijkstra_shortest_paths()算法,完整的源代码在例子examples/dijkstra-example.cpp中。Dijkstra 算法用来计算从起始顶点到其他顶点的最短路径。Dijkstra 算法要求设置每个边的权重和每个顶点的距离,这里我们把权重做为一个内在属性,距离作为外在属性。对于权重属性,我们创建属性类并指定int 作为权重类型,edge_weight_t 作为属性标记(一个BGL预定义的属性标记)。此权重属性类将作为邻接表adjacency_list 的一个模版参数

   选择listS或者vecS类型取决于我要在邻接表中使用的数据结构(可以看 Choosing the Edgelist and VertexList章节)。directedS 类型指定图为有向图(相对的是无向图)。后面的代码展示了一个图类型的声明和初始化,以及带权重属性的边如何传递给(使用迭代器作为参数的)图构造函数(要求随机迭代器)
typedef adjacency_list<listS, vecS, directedS, 
no_property, property<edge_weight_t, int> > Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef std::pair<int,int> E;

const int num_nodes = 5;
E edges[] = { E(0,2), 
E(1,1), E(1,3), E(1,4),
E(2,1), E(2,3), 
E(3,4),
E(4,0), E(4,1) };
int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1};
Graph G(edges + sizeof(edges) / sizeof(E), weights, num_nodes);

   对于外部距离属性,我们使用std::vector 来存储, BGL 算法视随机迭代器为property_maps。所以我们能够传递距离数组vector迭代器到Dijkstra's 算法。紧接上面的例子,下面的代码创建了一个distance vector, 然后调用Dijkstra's 算法(内部使用了权重属性),输出结果:
// vector for storing distance property
std::vector<int> d(num_vertices(G));
// get the first vertex
Vertex s = *(vertices(G).first);
// invoke variant 2 of Dijkstra's algorithm
dijkstra_shortest_paths(G, s, distance_map(&d[0]));

std::cout << "distances from start vertex:" << std::endl;
graph_traits<Graph>::vertex_iterator vi;
for(vi = vertices(G).first; vi != vertices(G).second; ++vi)
std::cout << "distance(" << index(*vi) << ") = " 
<< d[*vi] << std::endl;
std::cout << std::endl;

结果是:
distances from start vertex:
distance(0) = 0
distance(1) = 6
distance(2) = 1
distance(3) = 4
distance(4) = 5

使用Visitors扩充图算法

   通常一个库中的算法能够满足你大部分的需求,但事无绝对,例如在前面的章节中,我们使用Dijkstra's 算法来计算到每个顶点的最短路径,但可能我们想记录路径最短的树,可以通过在记录最短路径树中记录每个节点的前驱来实现。
    当然我们最好能够避免重写Dijkstra's 算法,并且只增加记录前辈节点的额外需求[1],在STL中,可以使用仿函数作为算法的可选参数来提供这种伸缩性。在BGL中,visitors 扮演着类似的角色。Visitor 类似stl仿函数。仿函数只有一个执行函数,但Visitor 拥有更多的方法,每个方法将在明确定义的算法点被调用。Visitor 函数在Visitor Concepts章节有详细说明。BGL 为通常的任务提供了几种visitor,包括记录前驱节点的visitor。作为扩充BGL的一种方法鼓励用户写自己的visitor。这里我们将迅速浏览实现和使用前驱记录,由于我们使用dijkstra_shortest_paths()算法,所以我们创建的visitor也必须是一个Dijkstra Visitor。record_predecessors visitor 的泛函性分成两部分。我们使用一个property map来存储和访问前驱属性。前驱 visitor 只负责记录前驱节点。为了实现这些,我们创建一个使用模版参数的record_predecessors类。由于这个visitor将在一个visitor方法中被填充,我们从一个提供空方法的dijkstra_visitor类继承。predecessor_recorder 类的构造函数将接受一个property map 对象,并把他保存在数据成员中。

template <class PredecessorMap>
class record_predecessors : public dijkstra_visitor<>
{
public:
record_predecessors(PredecessorMap p)
: m_predecessor(p) { }

template <class Edge, class Graph>
void edge_relaxed(Edge e, Graph& g) {
// set the parent of the target(e) to source(e)
put(m_predecessor, target(e, g), source(e, g));
}
protected:
PredecessorMap m_predecessor;
};
    记录前驱节点的工作十分简单,当Dijkstra's algorithm算法释放一个边的时候(添加他到最短路径树中) 我们记录源顶点作为目标顶点的前驱。稍后,如果边再次释放前驱属性将被新的前驱重写,这里我们使用put() 函数在property map中记录前驱。Visitor的edge_filter将告诉算法什么时候调用explore()方法。我们希望边在最短路径树中被通知,所以我们指定tree_edge_tag标记。最后,我们创建一个辅助函数来更方便的创建predecessor visitors,所有的BGL visitor 都有一个类似的辅助函数。  
template <class PredecessorMap> record_predecessors<PredecessorMap>
make_predecessor_recorder(PredecessorMap p) 
{
    return record_predecessors<PredecessorMap>(p);
}
   现在我们准备在Dijkstra's 算法中使用record_predecessors。BGL 的Dijkstra's 算法配备了一个vistitors句柄,所以我们只需要传入我们新的visitor即可。 在这个例子中我们只需要使用1个visitor,尽管BGL在算法中配置了多visitors句柄参数??(参见Visitor Concepts章).
using std::vector;
using std::cout;
using std::endl;
vector<Vertex> p(num_vertices(G)); //the predecessor 数组
dijkstra_shortest_paths(G, s, distance_map(&d[0]). 
visitor(make_predecessor_recorder(&p[0])));

cout << "parents in the tree of shortest paths:" << endl;
for(vi = vertices(G).first; vi != vertices(G).second; ++vi) {
cout << "parent(" << *vi;
if (p[*vi] == Vertex())
cout << ") = no parent" << endl; 
else 
cout << ") = " << p[*vi] << endl;
}
输出结果: 
parents in the tree of shortest paths:
parent(0) = no parent
parent(1) = 4
parent(2) = 0
parent(3) = 2
parent(4) = 3

注意:
新版本Dijkstra's algorithm包括了一个用来记录前驱的指定参数,所以前驱visitor 并不需要。但上面仍不失为一个好的例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值