2011-10-21 86 views
2

我正在做Boost :: Graph的第一步,遇到一些(對我)意想不到的行爲。助推圖的外部屬性表現怪異?

我想要的是具有一系列edge_weight屬性(該數字僅在運行時已知),並使用滿足某些約束條件的所有權重中的最小值。首先,typedef聲明:

typedef adjacency_list<vecS, vecS, undirectedS, property<vertex_distance_t, int>, property<edge_weight_t, int> > Graph; 
typedef graph_traits<Graph>::edge_descriptor Edge; 
typedef property_map<Graph, edge_weight_t>::type WeightMap; 
typedef property_map<Graph, vertex_distance_t>::type DistanceMap; 

我初始化圖形如下:

void testcase() { 
    int t, e, s, a, b; 
    cin >> t >> e >> s >> a >> b; 
    Graph g(t); 
    WeightMap fastestLinkWeight = get(edge_weight, g); 
    vector<WeightMap> weightMaps(s); 
    for (int i=0;i<e;i++) { 
     int u, v; 
     cin >> u >> v; 

     Edge edge; bool worked; 
     tie(edge, worked) = add_edge(u, v, g); 
     for (int j=0;j<s;j++) { 
      cin >> weightMaps[j][edge]; 
     } 
     fastestLinkWeight[edge] = INT_MAX; 

     cout << weightMaps[0][edge] << "\n"; 
    } 
} 

它反覆輸出INT_MAX。看起來像(外部)weightMaps[j]都是相同的,等於內部屬性fastestLinkWeight。但爲什麼?我怎樣才能確保我使用單獨的地圖?

回答

4

我能解決它。必須做的關鍵觀察:

WeightMap只是一個接口類型。如果它在問題代碼中被初始化,則行爲是未定義的。

相反,你需要存儲在容器中的數據,並確保它實現了根據界面(也就是get()put()operator[]方法爲the documentation on property maps解釋)。

定義將被用於到邊緣描述符翻譯成一個向量的元素的索引的EdgeIndexMap

在我的情況,該問題可以如下解決

typedef property_map<Graph, edge_index_t>::type EdgeIndexMap; 

iterator_property_map使用上述EdgeIndexMap類型:

typedef iterator_property_map<int*, EdgeIndexMap, int, int&> IterWeightMap; 

一個然後可以實例化一個使用在vector<vector<int> >提供的數據:

EdgeIndexMap eim = get(edge_index, g); 
vector<vector<int> > weights(s, vector<int>(e)); 
vector<IterWeightMap> weightMaps(s); 
for (int j=0;j<s;j++) { 
    weightMaps[j] = make_iterator_property_map(&(weights[j][0]), eim); 
} 

注意,edge_index屬性(天然地)被存儲爲內部屬性。

以這種方式,不同的edge_weight屬性可以在BGL算法中使用調用作爲通常,例如:

kruskal_minimum_spanning_tree(g, std::back_inserter(privateNetwork), weight_map(weightMaps[j]));