我正在尝试使用Boost Graph Library创建一个名为GraphService的类。 它应该计算图形上的各种内容,并将属性(如节点度分布)返回到其他类。这是我的图形头文件的一部分,称为Graph.h:
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
vertex_info, edge_info, graph_info, boost::listS> Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor VertexDescriptor;
typedef boost::graph_traits<Graph>::edge_descriptor EdgeDescriptor;
typedef boost::graph_traits<Graph>::vertex_iterator VertexIterator;
typedef boost::graph_traits<Graph>::edge_iterator EdgeIterator;
typedef boost::graph_traits<Graph>::adjacency_iterator AdjacencyIterator;
这是我的GraphService Headerfile的一部分:
#include "Graph.h"
class GraphService {
private:
Graph g;
public:
std::vector<int> get_adjacent(int i);
}
困扰我的部分是:
#include "Graph.h"
GraphService::GraphService(Graph graph) {
g = graph
}
std::vector<int> GraphService::get_adjacent(int i) {
AdjacencyIterator first, last;
std::vector<int> vertex_vector;
vertex_vector.push_back(i);
for (tie(first,last) = adjacent_vertices(i,g); first != last; ++first) {
vertex_vector.push_back(g[*first].id);
}
return vertex_vector;
}
我使用UnitTests测试了这个函数并且测试工作正常,但在我的编译器输出中,我看到以下错误消息;
/bin/sh: line 7: 20148 Segmentation fault build/Debug/GNU-Linux-x86/tests/TestFiles/f2
这似乎是指adjacency_iterator的错误。调试器告诉我,错误发生了,因为迭代器是最后一次。
我试图在脚本中运行相同的代码,其中图的创建和adjacent_vertices上的迭代在同一个函数中。一切都在那里正常工作。
有人可以帮忙吗?
提前致谢!
答案 0 :(得分:1)
我同意,特别是与您之前的问题有关,您可能在显示的代码之外有错误(Undefined Behaviour?)。
显示的代码可以正常工作,请参阅 SSCCE :
<强> Live On Coliru 强>
#include <boost/graph/adjacency_list.hpp>
#include <boost/multi_array.hpp>
using namespace boost;
struct vertex_info {
int id = []{ static int s_gen = 0; return ++s_gen; }();
};
struct edge_info {
};
struct graph_info {
};
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, vertex_info, edge_info, graph_info, boost::listS>
Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor VertexDescriptor;
typedef boost::graph_traits<Graph>::edge_descriptor EdgeDescriptor;
typedef boost::graph_traits<Graph>::vertex_iterator VertexIterator;
typedef boost::graph_traits<Graph>::edge_iterator EdgeIterator;
typedef boost::graph_traits<Graph>::adjacency_iterator AdjacencyIterator;
typedef multi_array<int, 3> array3i;
class GraphService {
private:
Graph g;
public:
GraphService(Graph graph) { g = graph; }
std::vector<int> get_adjacent(int i);
};
std::vector<int> GraphService::get_adjacent(int i)
{
AdjacencyIterator first, last;
std::vector<int> vertex_vector;
vertex_vector.push_back(i);
for (tie(first, last) = adjacent_vertices(i, g); first != last; ++first) {
vertex_vector.push_back(g[*first].id);
}
return vertex_vector;
}
#include <iostream>
#include <boost/graph/random.hpp>
#include <random>
int main() {
std::mt19937 prng { std::random_device{}() };
Graph example;
generate_random_graph(example, 100, 200, prng);
GraphService let_clone_that(example);
std::cout << "adjacent to 42: ";
for(int v: let_clone_that.get_adjacent(42))
std::cout << v << " ";
}
打印,例如
adjacent to 42: 42 71 38 3 14