我是 boost 图形库的新手,我想通过从文件中读取边列表来创建图形。
edge_list.dat
文件的示例是这样的:
...
123 445
4535 343
3432 454
123 345
123 566
...
文件的每一行代表图中的一条边,每行中的两个数字是该边对应的节点id。现在我想使用 boost 图形库从文件 edge_list.dat
创建一个图形。
但是,我事先并不知道图形的大小。我需要一路将顶点添加到图中。然而,像这样为每个顶点创建一个顶点描述符是不切实际的:
Graph::vertex_descriptor v0 = boost::add_vertex(g);
Graph::vertex_descriptor v1 = boost::add_vertex(g);
我想通过顶点 ID 访问顶点。我真的不知道该怎么做。现在我想出的解决方案是创建一个 map ,其键是 id,值是 vertex_descriptor
:
std::map<int,Graph::vertex_descriptor> VertexList;
VertexList[123]=boost::add_vertex(g);
但是,有没有一种方法可以在不创建 map 的情况下执行此操作?
提前致谢。
最佳答案
太棒了。雄心勃勃,呵呵:)
boost 图形库。和文本解析。让我们看看我们能做些什么:Boost Graph + Boost Spirit Qi = 良好的团队合作。
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/graph/edge_list.hpp>
#include <fstream>
typedef std::pair<int,int> Edge;
typedef std::vector<Edge> EdgeList;
typedef boost::edge_list<EdgeList::iterator> Graph;
namespace qi = boost::spirit::qi;
int main()
{
std::ifstream ifs("input.txt");
ifs >> std::noskipws;
boost::spirit::istream_iterator f(ifs), l;
std::vector<Edge> edges;
bool parse_ok = qi::phrase_parse(f, l, (qi::int_ >> qi::int_) % qi::eol, qi::blank, edges);
Graph g(edges.begin(), edges.end());
if (parse_ok)
{
std::cout << "Graph parsed with " << num_edges(g) << " edges\n";
} else
std::cout << "Parse error\n";
if (f!=l)
std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
打印(对于上面的有效输入行):
Graph parsed with 5 edges
Remaining unparsed input: '
'
关于c++ - 使用boost图形库: how to create a graph by reading edge lists from file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569535/