Boost/BGL/CreateGraph
From ProgrammingExamples
CreateGraph.cpp
#include <iostream> // for std::cout #include <utility> // for std::pair #include <algorithm> // for std::for_each #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> //using namespace boost; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS> Graph; int main(int,char*[]) { // Construct a graph Graph g(3); // 3 vertices add_edge(0, 1, g); add_edge(1, 2, g); // Get the vertices typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap; // "Ask a question" of a graph. The IndexMap is the solution set. IndexMap index = get(boost::vertex_index, g); std::cout << "vertices = "; typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter; std::pair<vertex_iter, vertex_iter> vertexPair; // The call to vertices(g) sets vp to (0, numberOfElements) // The loop, therefore, starts at 0, and increments the 'first' of the vertexPair // until it equals the 'second', which again is the numberOfElements. for (vertexPair = vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) { // You can see what is going on with this: //std::cout << "first: " << index[*vertexPair.first] << " second: " << index[*vp.second] << std::endl; // the vertex iterator // Or just output the vertex ids std::cout << index[*vertexPair.first] << " "; } std::cout << std::endl; std::cout << "edges = "; typedef boost::graph_traits<Graph>::edge_iterator edge_iter; std::pair<edge_iter, edge_iter> edgePair; for(edgePair = edges(g); edgePair.first != edgePair.second; ++edgePair.first) { std::cout << "(" << index[source(*edgePair.first, g)] << "," << index[target(*edgePair.first, g)] << ") "; } std::cout << std::endl; return 0; }
CMakeLists.txt
cmake_minimum_required(VERSION 2.6) Project(ConstructGraph) set(Boost_USE_MULTITHREADED ON) FIND_PACKAGE(Boost 1.38 COMPONENTS required) INCLUDE_DIRECTORIES(${INCLUDE_DIRECTORIES} ${Boost_INCLUDE_DIRS}) LINK_DIRECTORIES(${LINK_DIRECTORIES} ${Boost_LIBRARY_DIRS}) ADD_EXECUTABLE(ConstructGraph ConstructGraph.cpp) target_link_libraries(ConstructGraph)