Boost/BGL/BundledProperties

From ProgrammingExamples
< Boost‎ | BGL
Revision as of 17:53, 11 June 2011 by Awallin (Talk | contribs)

Jump to: navigation, search

BundledProperties.cpp

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
 
// Create a struct to hold several properties
struct MyProperty
{
  int MyIntProperty;
  std::string MyStringProperty;
};
 
// Define the type of the graph - this specifies a bundled property for vertices
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, MyProperty> Graph;
 
// Define the type of the graph - this specifies a bundled property for edges
//typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, MyProperty> Graph;
 
int main(int,char*[])
{
  // Create a graph object
  Graph g(2);
 
  boost::property_map<Graph, int MyProperty::*>::type MyIntPropertyMap = boost::get(&MyProperty::MyIntProperty, g);
  boost::put(MyIntPropertyMap, 0, 5);
  boost::put(MyIntPropertyMap, 1, 10);
 
  boost::property_map<Graph, std::string MyProperty::*>::type MyStringPropertyMap = boost::get(&MyProperty::MyStringProperty, g);
  boost::put(MyStringPropertyMap, 0, "TestName0");
  boost::put(MyStringPropertyMap, 1, "TestName1");
 
  // NOTE: the above code is equivalent to the slightly more elegant:
  // g[0].MyIntProperty = 5
  // g[1].MyIntProperty = 10
  // g[0].MyStringProperty = "TestName0"
  // g[1].MyStringProperty = "TestName1"
 
  typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;
  IndexMap index = get(boost::vertex_index, g);
 
  typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;
  std::pair<vertex_iter, vertex_iter> vertexPair;
  for (vertexPair = vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first)
    {
    std::cout << index[*vertexPair.first] <<  " : " << MyIntPropertyMap[*vertexPair.first] << " : " << MyStringPropertyMap[*vertexPair.first] <<  std::endl;
    }
 
  return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
 
Project(BundledProperties)
 
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(BundledProperties BundledProperties.cpp)
target_link_libraries(BundledProperties)