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

How do you add edges to boost::adjacency_matrix with property bundles?

我试图在具有捆绑的顶点和边属性的 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::adjacency_matrixboost::add_edge 重载中的断言失败,我得到了一个 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。目前有没有办法实现同样的事情?

你不知道。只是没有必要添加顶点,因为您已经使用所需的所有 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);

你能给矩阵添加顶点吗?

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