【问题标题】:Boost Graph with custom vertices and edges使用自定义顶点和边增强图
【发布时间】:2014-04-23 09:51:48
【问题描述】:

我正在使用自己的节点和边属性创建自定义提升图。 我将图表定义如下:

class NavGraph : public boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS, NodeInfo, EdgeInfo > {

public:
  typedef boost::graph_traits<NavGraph>::vertex_descriptor Vertex;
  typedef boost::graph_traits<NavGraph>::edge_descriptor Edge;

  NavGraph(){}

      void init(const std::vector<NodeInfo>& nodes, const std::vector<EdgeInfo>& edges);
}   

我现在要做的是从节点和边属性列表中初始化这个图(在 init 方法中)。 NodeInfo 和 EdgeInfo 是具有原始类型的简单结构。到目前为止,我已经这样做了:

void NavGraph::init(const std::vector<NodeInfo>& nodes, const std::vector<EdgeInfo>& edges){

  //Add the Vertices
    for (std::vector<NodeInfo>::const_iterator it = nodes.begin() ; it != nodes.end(); ++it){

        Vertex u = boost::add_vertex(*this);
        (*this)[u].nodeIndex = (*it).nodeIndex;
        (*this)[u].x = (*it).x;
        (*this)[u].y = (*it).y;
        (*this)[u].z = (*it).z;

    }

    //Add the edges
    for (std::vector<EdgeInfo>::const_iterator it = edges.begin() ; it != edges.end(); ++it){

    //To be implemented
    }

 }

所以,我设法添加了顶点并设置了属性(希望它是正确的)。现在,每个 EdgeInfo 都有一个源和目标 id,它们标识边缘的两个节点。问题是我需要通过 Id 从图中检索它们(使用我之前设置的 nodeIndex 属性),以便我可以调用 add_edge 方法。我真的不知道该怎么做。希望大家能帮帮我。

【问题讨论】:

    标签: c++ boost-graph


    【解决方案1】:

    从顶部开始:专门化邻接列表并向其中添加您自己的方法并不是一个好主意。

    相反,您应该创建 boost::adjacency_list 类的实例作为新类的成员,然后您可以为其编写方法。

    class cNavGraph {
      public:
      boost::adjacency_list < boost::vecS,
      boost::vecS,
      boost::undirectedS, 
      NodeInfo, EdgeInfo > myNavGraph;
    
    ...
    

    现在,要通过顶点属性 nodeIndex 从图中检索顶点,您有两种选择:

    1. 在顶点中搜索所需的 nodeIndex。这很简单,但如果图表非常大,会很慢。

    2. 在添加顶点时创建从 nodeIndex 到顶点的映射,然后在需要从 nodeIndex 获取顶点时在映射上进行查找。这需要更多的代码和内存,但对于大型图表会更快。

    作为一个更激进的建议,我建议重新设计一些东西,以便让 NodeIndex 和顶点描述符相同,就像这样

    for (std::vector<EdgeInfo>::const_iterator it = edges.begin() ;
       it != edges.end(); ++it)
    {
       add_edge( it->first_node_index,
                 it->second_node_index,
                 myGraph );
    

    请注意,在回复您的评论时,对 add_edge 的调用将自动添加两个顶点(如果它们尚不存在),顶点描述符等于指定的节点索引。不要调用 add_vertex!

    完成添加所有边后,您可以遍历节点,添加属性(任意数量)。

    【讨论】:

    • 非常感谢这些很棒的建议。现在我在地图上使用第二个选项,它似乎有效。对于第三种选择,如果我的 NodeInfo 中有多个属性,它是否有效?如何更改顶点描述符以将其设置为等于我的 nodeIndex?
    • 在答案正文中回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多