【问题标题】:Adding custom properties to vertex of a grid in Boost Graph Library在 Boost Graph Library 中向网格的顶点添加自定义属性
【发布时间】:2016-03-11 23:30:00
【问题描述】:

我在我的机器人项目中使用 Boost Graph Library 进行地图管理。我打算使用 Boost Grid,但我发现 Boost Graph 文档真的很难理解,所以我需要一点帮助。

这是我创建网格并打印它的方式:

  struct sampleVertex {
    int row;
    int col;
    bool occupied;
  };

  boost::array<std::size_t, 2> lengths = { { 3, 2 } };
  boost::grid_graph<2> gridD(lengths);
  boost::write_graphviz(fout, gridD);

现在,我想将自定义属性添加到顶点,定义为结构 - 'sampleVertex'。请给我看一些代码 sn-p 或示例来执行此操作。我知道,可以通过 adjacency_list 添加捆绑的属性并手动创建网格顶点和连接边。我想知道,是否可以直接使用 boost::grid_graph 来完成。提前致谢。

【问题讨论】:

    标签: c++ boost graph boost-graph


    【解决方案1】:

    这是我能想到的一个简单示例(它也使用了输出中的属性):

    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);
    }
    

    输出:

    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}" ;
    }
    

    【讨论】:

    • 您好,我需要将动态属性写入文件。我确实更改了流,但这给了我错误。知道我应该改变什么,将动态属性写入 DOT 文件。
    • 我的代码已经这样做了。太好了......也许你想展示你正在尝试做的事情(也许是一个新问题)。
    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多