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
17void boost::throw_exception(std::exception const& ex)
18{
19 std::cout << ex.what() << std::endl;
20 abort();
21}
22#endif
23
24using namespace boost;
25
26/// City structure to be attached to each vertex
27struct City
28{
29 City() {}
30
31 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
40namespace boost
41{
42namespace 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
62typedef adjacency_list< vecS, vecS, directedS, City > RoadMap;
63typedef graph_traits< RoadMap >::vertex_descriptor Vertex;
64
65int main(int, char*[])
66{
67 RoadMap map;
68
69 /// Create vertices for Bloomington, Indianapolis, Chicago
70 Vertex bloomington = add_vertex(p: City("Bloomington", 69291), g_&: map);
71 Vertex indianapolis = add_vertex(p: City("Indianapolis", 791926), g_&: map);
72 Vertex chicago = add_vertex(p: City("Chicago", 9500000), g_&: 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(u: bloomington, v_name: "Indianapolis", g&: map);
85 add_edge(u_name: "Indianapolis", v: chicago, g&: map);
86 add_edge(u_name: "Indianapolis", v_name: "Cincinnatti", g&: map);
87
88 BGL_FORALL_EDGES(road, map, RoadMap)
89 std::cout << map[source(e: road, map)].name << " -> "
90 << map[target(e: road, map)].name << std::endl;
91
92 BOOST_TEST(map[*find_vertex("Cincinnatti", map)].population == -1);
93
94 return boost::report_errors();
95}
96

source code of boost/libs/graph/test/named_vertices_test.cpp