2011-10-21 18 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]));