2015-11-16 22 views
2

我在努力將boost::graph算法的使用轉化爲一組新的實現類。我想知道:如果boost::graph只存儲std::shared_ptr引用,是否可以訪問對象的屬性?就像下面這個:在boost :: graph中訪問std :: shared_ptr的成員函數?

class Vert { 
public: 
    Vert(); 
    Vert(std::string n); 
    std::string getName() const; 
    void setName(std::string const& n); 
private: 
    std::string name; 

}; 
typedef std::shared_ptr<Vert> Vert_ptr; 

using namespace boost; 
typedef boost::adjacency_list<vecS, vecS, directedS, Vert_ptr> Graph; 
Graph g; 
Vert_ptr a(new Vert("a")); 
add_vertex(a, g); 
std::ofstream dot("test.dot"); 
write_graphviz(dot, g, make_label_writer(boost::get(&Vert::getName,g))); //ERROR! 

是否有可能訪問std::shared_ptr成員在圖形標籤寫入write_graphviz或執行任何其他屬性使用?

謝謝!

回答

3

呀只需使用一個轉換屬性映射

Live On Coliru

#include <boost/graph/adjacency_list.hpp> 
#include <boost/graph/graphviz.hpp> 
#include <boost/property_map/transform_value_property_map.hpp> 
#include <fstream> 
#include <memory> 

using namespace boost; 

class Vert { 
public: 
    Vert(std::string n="") : name(n) { } 
    std::string getName() const { return name; } 
    void setName(std::string const& n) { name = n; } 
private: 
    std::string name; 
}; 

typedef std::shared_ptr<Vert> Vert_ptr; 

struct Name { std::string operator()(Vert_ptr const& sp) const { return sp->getName(); } }; 

int main() { 
    typedef boost::adjacency_list<vecS, vecS, directedS, Vert_ptr> Graph; 
    Graph g; 
    Vert_ptr a(new Vert("a")); 
    add_vertex(a, g); 
    std::ofstream dot("test.dot"); 
    auto name = boost::make_transform_value_property_map(Name{}, get(vertex_bundle,g)); 
    write_graphviz(dot, g, make_label_writer(name)); 
} 

結果:

digraph G { 
0[label=a]; 
} 
+0

謝謝你...雖然我目前的升壓版本(V1.50)我不相信'make_transform_value_property_map'我相信。之後,我必須檢查我的編譯器(MSVC2010)是否支持這種'Name {}'語法。 – Hhut

+1

替換爲'Name()'... – sehe

+0

2012年3月25日引入的變換值屬性映射r77535,意思是至少在1.56。我有另一種想法。不掛斷 – sehe

相關問題