摘自 《The Boost Graph Library》
代码示例在 vc2012下编译通过。
图类与适配器
1.类
adjacency_list 用于稀疏图,用例如下:
#include <iostream>
#include <vector>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/tuple/tuple.hpp>
enum family { Jeanie, Debbie, Rick, John, Amanda, Margaret, Benjamin, N };
int main()
{
using namespace boost;
const char *name[] = {"Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin"};
adjacency_list<> g(N);
add_edge(Jeanie,Debbie,g);
add_edge(Jeanie,Rick,g);
add_edge(Jeanie,John,g);
add_edge(Debbie,Amanda,g);
add_edge(Rick,Margaret,g);
add_edge(John,Benjamin,g);
graph_traits<adjacency_list<> >::vertex_iterator i,end;
graph_traits<adjacency_list<> >::adjacency_iterator ai,a_end;
property_map<adjacency_list<>,vertex_index_t>::type index_map = get(vertex_index,g);
for(tie(i,end) = vertices(g); i != end; ++i) {
std::cout << name[get(index_map,*i)];
boost::tie(ai,a_end) = adjacent_vertices(*i, g);
if(ai == a_end)
std::cout << " has no children.";
else
std::cout << " is the parent of ";
for(; ai != a_end; ++ai) {
std::cout << name[get(index_map, *ai)];
if(boost::next(ai) != a_end)
std::cout << ", ";
}
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
2. 拓扑排序算法
#include <deque>
#include <vector>
#include <list>
#include <iostream>
#include <boost/graph/vector_as_graph.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/adjacency_list.hpp>
int main()
{
using namespace boost;
const char *tasks[] = {
"pick up kids from school",
"buy groceries snacks",
"get cash at ATM",
"drop off kids at soccer practice",
"cook dinner",
"pick up kids from soccer",
"eat dinner",
"before drop off"
};
const int n_tasks = sizeof(tasks) / sizeof(char*);
/*
std::vector<std::list<int> > g(n_tasks);
g[0].push_back(3);
g[1].push_back(3);
g[1].push_back(4);
g[2].push_back(1);
g[3].push_back(5);
g[4].push_back(6);
g[5].push_back(6);
*/
adjacency_list<listS,vecS,directedS> g(n_tasks);
add_edge(7,3,g);
add_edge(0,3,g);
add_edge(1,3,g);
add_edge(1,4,g);
add_edge(2,1,g);
add_edge(3,5,g);
add_edge(5,6,g);
add_edge(4,6,g);
//perform the topological sort and output the result
std::deque<int> topo_order;
topological_sort(g, std::front_inserter(topo_order),
vertex_index_map(identity_property_map()));
int n = 1;
for(std::deque<int>::iterator i=topo_order.begin();
i != topo_order.end(); ++i, ++n)
std::cout << tasks[*i] << std::endl;
return EXIT_SUCCESS;
}
今天还学习了 BCCL 库,即 Boost concept check library, 检查模型是否满足模板要求并提供较精准的编译错误信息。
关于如何存取BGL的算法: 应加boost前缀,如 boost:breadth_first_search