Boost Graph库是一个性能不错的图算法库,就是概念有点晦涩。今天写一个小程序进行简单的学习,下面将代码记录下来备查。
1. main.cpp
#include <boost/graph/adjacency_list.hpp>
#include <iostream>
int main() {
// Property types
typedef boost::property<boost::edge_weight_t, int> EdgeWeightProperty;
typedef boost::property<boost::vertex_name_t, std::string,
boost::property<boost::vertex_index2_t, int> > VertexProperties;
// Graph type
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
VertexProperties, EdgeWeightProperty> Graph;
// Graph instance
Graph g;
// Property accessors
boost::property_map<Graph, boost::vertex_name_t>::type city_name =
boost::get(boost::vertex_name, g);
boost::property_map<Graph, boost::vertex_index2_t>::type city_index2 =
boost::get(boost::vertex_index2, g);
boost::property_map<Graph, boost::edge_weight_t>::type edge_distance =
boost::get(boost::edge_weight, g);
// Create the vertices
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
Vertex u1 = boost::add_vertex(g);
city_name[u1] = "Los Angeles";
city_index2[u1] = 3;
Vertex u2 = boost::add_vertex(g);
city_name[u2] = "Bakersfield";
city_index2[u2] = 2;
Vertex u3 = boost::add_vertex(g);
city_name[u3] = "New York";
city_index2[u3] = 1;
// Create the edges
typedef boost::graph_traits<Graph>::edge_descriptor Edge;
Edge e1 = (boost::add_edge(u1, u2, g)).first;
edge_distance[e1] = 100;
Edge e2 = (boost::add_edge(u1, u3, g)).first;
edge_distance[e2] = 2500;
// Iterate through the vertices and print them out
typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vp;
std::cout << "Vertices of the graph g: " << std::endl;
for (vp = boost::vertices(g); vp.first != vp.second; ++vp.first)
{
std::cout << city_name[*vp.first] << " " << city_index2[*vp.first] << std::endl;
}
std::cout << std::endl;
// Iterate through the edges and print them out
typedef boost::graph_traits<Graph>::edge_iterator edge_iter;
edge_iter ei, ei_end;
std::cout << "Edges of the graph g: " << std::endl;
for (std::tie(ei, ei_end) = boost::edges(g); ei != ei_end; ++ei)
{
std::cout << edge_distance[*ei] << std::endl;
}
return 0;
}
2. CMakeLists.txt
使用CMake生成Makefile,CMakeLists.txt内容如下:
cmake_minimum_required(VERSION 3.9)
project(graph)
set(CMAKE_CXX_STANDARD 11)
set(BOOST_INCLUDE_PATH "$ENV{HOME}/code/boost_1_66_0")
include_directories(${BOOST_INCLUDE_PATH})
add_executable(graph main.cpp)
说明:我将下载后的Boost 1.66.0解压后放置于/home/davidhopper/code/boost_1_66_0目录下。