2010-08-04 19 views
0

我正在嘗試使用Boost Graph Library。我想打印出我的圖形的拓撲排序。然而,我想在我的圖表上輸出的是頂點的實際名稱,而不是數字位置。例如,在下面的例子:使用Boost圖庫以拓撲順序打印頂點的名稱

typedef boost::adjacency_list<vecS, vecS, directedS, 
           property<vertex_name_t, std::string>, 
           property<edge_weight_t, int> > Graph; 

typedef boost::graph_traits<Graph>::vertex_descriptor Vertex; 
typedef std::vector<Vertex> container; 
Graph g; 
BOOST_CHECK(read_graphviz(in, g, dp, "id")); 
container c; 
topological_sort(g, std::back_inserter(c)); 

std::cout << "A topological ordering: "; 
for (container::reverse_iterator ii=c.rbegin(); ii!=c.rend(); ++ii) 
    std::cout <<*ii<<" ";            
std:: cout <<std::endl; 

我得到以下輸出:

A topological ordering: 45 40 41 34 35 33 43 30 31 36 32 26 27 25 23 24 19 46 47 18 48 17 20 21 49 50 16 51 15 44 14 22 42 13 37 38 9 11 28 29 12 7 39 6 8 5 10 3 4 0 2 1 

這些值是有序的頂點的位置,但我寧願有每個頂點的名字。有誰知道如何做到這一點?

回答

2

嗯,這個通用編程讓我困惑:)試試這段代碼。至少應該編譯它!

std::cout << get(vertex_name, g, *ii) << " "; 
+0

謝謝你的工作! – user411287 2010-08-05 00:12:35

3

我一直覺得它更容易使用自定義節點/邊緣類中使用BGL時工作:

struct Node { 
    int x; 
    int y; 
    std::string name; 
}; 

struct Edge { 
    int weight; 
}; 

//boost:: qualifiers removed for brevity 
typedef adjacency_list<vecS, vecS, directedS, Node, Edge> Graph; 

... 
{ 
    Graph g; 
    Graph::vertex_descriptor v = ...; 

    g[v].x = 1; 
    std::cout << g[v].name << std::endl; 
} 

但是,是的,作爲*ii是一個頂點描述符,你應該能夠使用它就像@Tom Sirgedas提到的那樣。 (當我寫我的時候,他發佈了他的答案)

+0

感謝您的諮詢! – user411287 2010-08-05 00:12:54