1 // Copyright (C) 2007-2008 The Trustees of Indiana University.
2
3 // Use, modification and distribution is subject to the Boost Software
4 // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6
7 // Test support for named vertices in adjacency_list.
8 #include <boost/config.hpp>
9 #include <boost/throw_exception.hpp>
10 #include <boost/core/lightweight_test.hpp>
11 #include <boost/graph/adjacency_list.hpp>
12 #include <boost/graph/iteration_macros.hpp>
13 #include <string>
14 #include <iostream>
15
16 #ifdef BOOST_NO_EXCEPTIONS
throw_exception(std::exception const & ex)17 void boost::throw_exception(std::exception const& ex)
18 {
19 std::cout << ex.what() << std::endl;
20 abort();
21 }
22 #endif
23
24 using namespace boost;
25
26 /// City structure to be attached to each vertex
27 struct City
28 {
CityCity29 City() {}
30
CityCity31 City(const std::string& name, int population = -1)
32 : name(name), population(population)
33 {
34 }
35
36 std::string name;
37 int population;
38 };
39
40 namespace boost
41 {
42 namespace graph
43 {
44
45 /// Use the City name as a key for indexing cities in a graph
46 template <> struct internal_vertex_name< City >
47 {
48 typedef multi_index::member< City, std::string, &City::name > type;
49 };
50
51 /// Allow the graph to build cities given only their names (filling in
52 /// the defaults for fields).
53 template <> struct internal_vertex_constructor< City >
54 {
55 typedef vertex_from_name< City > type;
56 };
57
58 }
59 } // end namespace boost::graph
60
61 /// Our road map, where each of the vertices are cities
62 typedef adjacency_list< vecS, vecS, directedS, City > RoadMap;
63 typedef graph_traits< RoadMap >::vertex_descriptor Vertex;
64
main(int,char * [])65 int main(int, char*[])
66 {
67 RoadMap map;
68
69 /// Create vertices for Bloomington, Indianapolis, Chicago
70 Vertex bloomington = add_vertex(City("Bloomington", 69291), map);
71 Vertex indianapolis = add_vertex(City("Indianapolis", 791926), map);
72 Vertex chicago = add_vertex(City("Chicago", 9500000), map);
73
74 BOOST_TEST(add_vertex(City("Bloomington", 69291), map) == bloomington);
75
76 BGL_FORALL_VERTICES(city, map, RoadMap)
77 std::cout << map[city].name << ", population " << map[city].population
78 << std::endl;
79
80 BOOST_TEST(*find_vertex("Bloomington", map) == bloomington);
81 BOOST_TEST(*find_vertex("Indianapolis", map) == indianapolis);
82 BOOST_TEST(*find_vertex("Chicago", map) == chicago);
83
84 add_edge(bloomington, "Indianapolis", map);
85 add_edge("Indianapolis", chicago, map);
86 add_edge("Indianapolis", "Cincinnatti", map);
87
88 BGL_FORALL_EDGES(road, map, RoadMap)
89 std::cout << map[source(road, map)].name << " -> "
90 << map[target(road, map)].name << std::endl;
91
92 BOOST_TEST(map[*find_vertex("Cincinnatti", map)].population == -1);
93
94 return boost::report_errors();
95 }
96