2015-12-07 59 views
3

我在我的機器人項目中使用Boost圖庫進行地圖管理。我打算使用Boost Grid,我發現Boost Graph文檔很難理解,所以我需要一些幫助。將自定義屬性添加到Boost圖庫中的網格頂點

這是我所創建的網格的方式,進行打印:

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」。請給我看一些代碼片段或例子來做到這一點。我知道,捆綁的屬性可以通過adjacency_list添加並手動創建網格頂點和連接邊。我想知道,如果它可以直接使用boost :: grid_graph完成。提前致謝。

回答

4

下面是一個簡單的例子,我可以想出(其也使用在輸出屬性):

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

您好sehe ,我有要求將動態屬性寫入文件。我確實改變了流,但那給了我錯誤。任何想法我應該改變,將動態屬性寫入DOT文件。 – soupso

+0

我的代碼已經做到了。 Sooo ...也許你想展示你想要做什麼(也許是一個新問題)。 – sehe

相關問題