Adding custom properties to vertex of a grid in Boost Graph Library

醉酒当歌 提交于 2019-12-01 21:52:24

Here's a simple example I can come up with (which also uses the properties in the output):

Live On Coliru

#include <boost/graph/grid_graph.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/graphviz.hpp>
#include <iostream>

struct sampleVertex {
    int row;
    int col;
    bool occupied;
    friend std::ostream& operator<<(std::ostream& os, sampleVertex& sv) {
        return os << "{" << sv.row << "," << sv.col << "," << sv.occupied << "}";
    }
    friend std::istream& operator>>(std::istream& is, sampleVertex& sv) {
        return is >> sv.row >> sv.col >> sv.occupied;
    }
};


int main() {
    boost::array<int, 2> lengths = { { 3, 2 } };
    using Graph  = boost::grid_graph<2, int>;
    using Traits = boost::graph_traits<Graph>;
    using IdMap  = boost::property_map<Graph, boost::vertex_index_t>::const_type;

    Graph gridD(lengths);
    IdMap indexMap(get(boost::vertex_index, gridD));
    // properties
    boost::vector_property_map<sampleVertex, IdMap> props(num_vertices(gridD), indexMap);

    // initialize
    for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 2; ++j)
            put(props, Traits::vertex_descriptor {{i, j}}, sampleVertex{i,j,false});

    // print a property
    boost::dynamic_properties dp;
    dp.property("node_id", props);
    boost::write_graphviz_dp(std::cout, gridD, dp);
}

Output:

digraph G {
"{0,0,0}";
"{1,0,0}";
"{2,0,0}";
"{0,1,0}";
"{1,1,0}";
"{2,1,0}";
"{0,0,0}"->"{1,0,0}" ;
"{1,0,0}"->"{2,0,0}" ;
"{0,1,0}"->"{1,1,0}" ;
"{1,1,0}"->"{2,1,0}" ;
"{1,0,0}"->"{0,0,0}" ;
"{2,0,0}"->"{1,0,0}" ;
"{1,1,0}"->"{0,1,0}" ;
"{2,1,0}"->"{1,1,0}" ;
"{0,0,0}"->"{0,1,0}" ;
"{1,0,0}"->"{1,1,0}" ;
"{2,0,0}"->"{2,1,0}" ;
"{0,1,0}"->"{0,0,0}" ;
"{1,1,0}"->"{1,0,0}" ;
"{2,1,0}"->"{2,0,0}" ;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!