我正在学习使用 Boost 图形库。我已经按照此处的说明定义了一个自定义结构来存储有关顶点的信息:Modifying vertex properties in a Boost::Graph .
struct VertexProperties {
int attribute1;
string attribute2;
};
typedef adjacency_list<vecS, vecS, directedS, VertexProperties, no_property> Graph;
我可以像这样简单地迭代图顶点并修改它们的属性:
for (int i = 0; i < num_vertices(g); i++)
{
g[i].attribute1 = 123;
g[i].attribute2 = "123";
}
但是当我只有一个顶点迭代器时,我如何真正获得这些属性(即 VertexProperties 的相应实例)?
GraphTraits::vertex_iterator vert_i, vert_end;
for (tie(vert_i, vert_end) = vertices(g); vert_i != vert_end; ++vert_i){
//how do i get to "vert_i.attribute1" ?
}
同样的问题也适用于边和边迭代器。它应该很容易,但我似乎无法在 BGL 文档或其他任何地方找到它。
感谢您的帮助。
最佳答案
使用 g[*vert_i].attribute1
应该可以。这是指定的方式,它确实有效。如果您查看 bundled properties 上的文档页面,它说:
To access a bundled property for a particular edge or vertex, subscript your graph with the descriptor of the edge or vertex whose bundled property you wish to access.
他们给出了例子:
Graph g;
Graph::vertex_descriptor v = *vertices(g).first;
g[v].name = "Troy";
vertex_iterator
类型应该取消引用到 vertex_descriptor
中,您应该使用它来下标到图中 (g[v]
)。因此,使用 g[*vert_i].attribute1
绝对有效。如果不是,则这是您需要在跟踪器上提交的错误。
所以,这也意味着你的原始代码,g[i].attribute1
,是不正确的,因为不能保证整数索引一定与 vertex_descriptor 相同
该图的类型(它恰好有效,因为您使用 vecS
作为 VertexList
参数,这使得 vertex_descriptor
成为一个整数,但它不一定是,即使使用 vecS
)。您应该只使用 vertex_descriptor
对象来索引图中。此外,如果您的 g[i]
代码有效,那么 g[*vert_i]
也应该有效,根本不可能一个可以工作而另一个不能, 除非有严重的错误。
但是请注意,我知道捆绑属性在某些情况下会被禁用。特别是,它使用了一些编译器可能不支持的技术,这意味着旧的或奇特的编译器可能无法完成这项工作。这是一个缺陷,我希望将来能够通过完全检查当前 adjacency_list
类模板的替代实现来消除,但如此彻底的重新设计不太可能进入 BGL,直到一些时间。
访问捆绑属性的另一种方法是使用它的属性映射,它有一些讨厌的语法,但可能有更大的工作机会。对于您的示例,它将是这样的:
boost::property_map<Graph, int VertexProperties::*>::type attr1 =
get(&VertexProperties::attribute1, g);
GraphTraits::vertex_iterator vert_i, vert_end;
for (tie(vert_i, vert_end) = vertices(g); vert_i != vert_end; ++vert_i){
put(attr1, *vert_i, 123);
}
还有一个不受支持的功能(底层),用于获取整个包的属性映射,但您不能使用它,因为它不是受支持接口(interface)的一部分。
关于c++ - BGL : How to get custom vertex properties class instance from vertex iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26495896/