如何使用属性包向boost :: adjacency_matrix添加边?

时间:2018-02-04 20:37:51

标签: c++ boost boost-graph

我试图在带有捆绑顶点和边缘属性的boost :: adjacency_matrix图中添加边。

代码如下:

// VD and ED are just trivial structs
using Graph = boost::adjacency_matrix<boost::directedS, VD, ED>;
using Vertex = boost::graph_traits<Graph>::vertex_descriptor;
using Edge = boost::graph_traits<Graph>::edge_descriptor;

const unsigned kNodesCount = 4;
Graph g { kNodesCount };

// create two nodes
auto one = boost::add_vertex(g);
auto two = boost::add_vertex(g);

// add edge between nodes (vertices)
boost::add_edge(one, two, g);

由于boost::add_edge boost::adjacency_matrix重载内的断言失败,我收到了SIGABRT。事实证明它是 UNDER CONSTRUCTION (与邻接矩阵的一些其他函数一样)。

   template <typename D, typename VP, typename EP, typename GP, typename A>
  inline typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor
  add_vertex(adjacency_matrix<D,VP,EP,GP,A>& g) {
    // UNDER CONSTRUCTION
    BOOST_ASSERT(false);
    return *vertices(g).first;
  }

  template <typename D, typename VP, typename EP, typename GP, typename A,
            typename VP2>
  inline typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor
  add_vertex(const VP2& /*vp*/, adjacency_matrix<D,VP,EP,GP,A>& g) {
    // UNDER CONSTRUCTION
    BOOST_ASSERT(false);
    return *vertices(g).first;
  }

  template <typename D, typename VP, typename EP, typename GP, typename A>
  inline void
  remove_vertex(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor /*u*/,
                adjacency_matrix<D,VP,EP,GP,A>& /*g*/)
  {
    // UNDER CONSTRUCTION
    BOOST_ASSERT(false);
  }

所以,我的问题是:我们如何解决这个问题?我在网上找到的所有示例都使用boost::adjacency_list。目前有没有办法实现同样的目标?

1 个答案:

答案 0 :(得分:1)

你不是。它不需要添加顶点,因为您已经使用所需的所有kNodesCount对其进行了初始化。相反,获取现有顶点的顶点描述符:

<强> Live On Coliru

#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/graph_utility.hpp>
struct VD { };
struct ED { };

// VD and ED are just trivial structs
using Graph  = boost::adjacency_matrix<boost::directedS, VD, ED>;
using Vertex = Graph::vertex_descriptor;
using Edge   = Graph::edge_descriptor;

int main() {
    const unsigned kNodesCount = 4;
    Graph g { kNodesCount };

    // create two nodes
    Vertex one = vertex(0, g);
    Vertex two = vertex(1, g);

    // add edge between nodes (vertices)
    add_edge(one, two, g);
    print_graph(g);
}

打印

0 --> 1 
1 --> 
2 --> 
3 --> 

事实上,由于adjacency_matrix<>模型中顶点描述符的微不足道性质,您可以对顶点描述符进行硬编码,如:

<强> Live On Coliru

add_edge(0, 1, g);

您可以将顶点添加到矩阵中吗?

不,不是动态的。支持的操作列在