【问题标题】:How to read a graph from a file using boost?如何使用 boost 从文件中读取图形?
【发布时间】:2016-06-04 13:17:56
【问题描述】:

我想使用 boost 从文件中读取图表。输入文件包含边数,然后是成对的边。我想打印邻接列表。我尝试了以下代码。请帮帮我

    #include <boost/graph/adjacency_list.hpp>
#include <fstream>
#include <boost/graph/graphviz.hpp>
using namespace std;
using namespace boost;
int main(){
    typedef adjacency_list <listS, vecS, directedS> Graph;

    typedef graph_traits<Graph>::vertex_descriptor index_vertex;
    typedef boost::graph_traits <Graph>::edge_iterator edgeIt;
    typedef boost::graph_traits<Graph>::vertex_iterator vertexIt;
    // declare a graph object
    Graph G;
    std::ifstream infile("di.dat");
    index_vertex n_vertices;
    //int n_vertices;
    if(infile >> n_vertices){
        std::cout << n_vertices << endl; // read in number of vertices
    }
    while(infile)
    {
        int f;
        int s;
        infile >> f>> s;
        // std::cout<<first<<second;
        add_edge(f, s, G);     
    }
    infile.close();
    for(pair<vertexIt,vertexIt> vi = boost::vertices(G); vi.first != vi.second; ++vi.first) {
        cout << *vi.first << endl;
    }
    for(pair<edgeIt,edgeIt> ei = boost::edges(G); ei.first != ei.second; ++ei.first) {
        cout << source(*ei.first, G) << " -> " << target(*ei.first, G) << endl;
        //cout << *ei.first << endl;
    }


    ofstream dotfile;
    dotfile.open("test1.dot");
    write_graphviz(dotfile, G);
    system("xdot test1.dot");
    return 0;
}

输入是

14
1 2
2 3
3 4
3 5
4 6
6 7
7 8
7 9
7 10
8 11
9 12

12 13
13 14

【问题讨论】:

  • 如果您包含错误消息以及您正在使用的平台和编译器,将会很有帮助。
  • 如果将for循环更改为for (int i=0; ei != ei_end; ++ei, ++i),则可以完全删除ei_next。

标签: c++ file boost graph


【解决方案1】:

说明问题所在的基本示例如下:

#include <iostream>

int main(int argc, char**argv)
{
     char j;

     for (int i=0, j='a'; j<'d'; i++, j++)
     {
         std::cout << j << std::endl;
     }

     std::cout << "++++++++++" << std::endl;

         for (j='a'; j<'d';j++)
     {
         std::cout << j << std::endl;
     }

    return 0;
}

输出:

97
98
99
++++++++++
a
b
c

这是引发此错误的基本示例。用int 初始化edge_iterator。正如@Marvin 所说,重新访问您的循环。

【讨论】:

  • 为什么要多打印一个顶点?任何的想法? 0 被打印
【解决方案2】:

for 循环中的int i=0, ei_next = ei; 定义了一个新的本地int 变量ei_next,因为在这种情况下逗号不是逗号操作符而是定义分隔符。 由于ei 是edge_iterator,它不能用于初始化int 变量ei_next。

将ei_next = ei 移动到for 语句之前的行中(添加分号)以使其成为赋值。

【讨论】:

  • 14 10Edges n° 0 : 源 1 - 目标 0
  • 输入是什么?预期的输出是什么?
  • 在输入文件中尝试使用空格作为分隔符。我认为1,2 不会与infile &gt;&gt; first &gt;&gt; second; 一起使用。
  • Y 0 打印为顶点 .total 15 vertices.but 实际顶点为 14
  • 在读取文件infile 中的最后一个条目后,在while 循环中仍然评估为真,从而导致读取附加值对。 infile 为假,但无论如何都会添加无效边缘。尝试在输入行后添加if (!infile) break;。
猜你喜欢
  • 2014-04-29
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2019-09-11
  • 2014-02-21
相关资源
最近更新 更多