使用boost图形库:如何通过从文件中读取边列表创建一个图表 [英] Using boost graph library: how to create a graph by reading edge lists from file

查看:251
本文介绍了使用boost图形库:如何通过从文件中读取边列表创建一个图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来提高图形库,我想用从文件中读取边列表创建一个图表。

I'm new to boost graph library and I'd like to create a graph by reading edge lists from a file.

edge_list.dat 文件的示例是这样的:

A sample of the edge_list.dat file is this:

...
123 445
4535 343
3432 454
123 345
123 566
...

文件重新presents图的每行中的两个数字的边缘,并且每行是对应于边缘节点的标识。现在我想使用Boost图库 edge_list.dat 从文件创建一个图形。

Each line of the file represents an edge of the graph, and the two numbers in each line are the nodes' ids corresponding to the edge. Now I'd like to create a graph from the file edge_list.dat using boost graph library.

不过,我不知道该图提前大小。我需要顶点添加到沿途的曲线图。然而,它是不实际的创建顶点描述符这样每个顶点:

However, I don't know the size of the graph in advance. I need to add the vertex into the graph along the way. However it is not practical to create a vertex descriptor for each vertex like this:

Graph::vertex_descriptor v0 = boost::add_vertex(g);
Graph::vertex_descriptor v1 = boost::add_vertex(g);

和我想通过顶点标识访问顶点。我真的不知道如何做到这一点。现在,我拿出解决方案是创建一个地图它的键是id和值是 vertex_descriptor的

And I'd like to access the vertex through the vertex id. I don't really know how to do this. For now the solution that I come up with is to create a map for which the key is the id and the value is the vertex_descriptor:

std::map<int,Graph::vertex_descriptor> VertexList;
VertexList[123]=boost::add_vertex(g);

不过是有办法,我可以做到这一点,而无需创建地图?

However is there a way that I can do this without creating the map?

先谢谢了。

推荐答案

SOOOO。雄心勃勃的,呵呵:)

Soooo. Ambitious, huh :)

Boost图库。和文本分析。让我们看看我们能做些什么:提升图形+升压灵奇=好的团队精神

Boost Graph library. And text parsing. Let's see what we can do: Boost Graph + Boost Spirit Qi = nice teamwork.

看它的 住在Coliru

See it Live On Coliru

#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";
}

打印(以上有效输入线):

Prints (for the valid input lines above):

Graph parsed with 5 edges
Remaining unparsed input: '
'

这篇关于使用boost图形库:如何通过从文件中读取边列表创建一个图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆