graph_as_tree.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //=======================================================================
  2. // Copyright 2002 Indiana University.
  3. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See
  6. // accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //=======================================================================
  9. #include <boost/graph/graph_as_tree.hpp>
  10. #include <boost/graph/adjacency_list.hpp>
  11. #include <boost/cstdlib.hpp>
  12. #include <iostream>
  13. class tree_printer {
  14. public:
  15. template <typename Node, typename Tree>
  16. void preorder(Node, Tree&) {
  17. std::cout << "(";
  18. }
  19. template <typename Node, typename Tree>
  20. void inorder(Node n, Tree& t)
  21. {
  22. std::cout << get(boost::vertex_name, t)[n];
  23. }
  24. template <typename Node, typename Tree>
  25. void postorder(Node, Tree&) {
  26. std::cout << ")";
  27. }
  28. };
  29. int main()
  30. {
  31. using namespace boost;
  32. typedef adjacency_list<vecS, vecS, directedS,
  33. property<vertex_name_t, std::string> > graph_t;
  34. typedef graph_traits<graph_t>::vertex_descriptor vertex_t;
  35. graph_t g;
  36. vertex_t a = add_vertex(g),
  37. b = add_vertex(g),
  38. c = add_vertex(g);
  39. add_edge(a, b, g);
  40. add_edge(a, c, g);
  41. typedef property_map<graph_t, vertex_name_t>::type vertex_name_map_t;
  42. vertex_name_map_t name = get(vertex_name, g);
  43. name[a] = "A";
  44. name[b] = "B";
  45. name[c] = "C";
  46. typedef iterator_property_map<std::vector<vertex_t>::iterator,
  47. property_map<graph_t, vertex_index_t>::type> parent_map_t;
  48. std::vector<vertex_t> parent(num_vertices(g));
  49. typedef graph_as_tree<graph_t, parent_map_t> tree_t;
  50. tree_t t(g, a, make_iterator_property_map(parent.begin(),
  51. get(vertex_index, g)));
  52. tree_printer vis;
  53. traverse_tree(a, t, vis);
  54. return exit_success;
  55. }