c – 使用boost图库:如何通过从文件中读取边列表来创建图形

前端之家收集整理的这篇文章主要介绍了c – 使用boost图库:如何通过从文件中读取边列表来创建图形前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_1@我是新手来增强图形库,我想通过从文件中读取边缘列表来创建图形.

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访问顶点.我真的不知道该怎么做.现在,我提出的解决方案是创建一个映射,其中键是id,值是vertex_descriptor:

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

但是有没有办法可以在不创建地图的情况下做到这一点?

提前致谢.

解决方法

SOOOO.雄心勃勃,呵呵:)

Boost图形库.和文本解析.让我们看看我们能做些什么:提升图形提升精神气氛=良好的团队合作.

见它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";
}

打印(对于上面的有效输入行):

Graph parsed with 5 edges
Remaining unparsed input: '
'
原文链接:https://www.f2er.com/c/118929.html

猜你在找的C&C++相关文章