首页 > 解决方案 > 在c ++中输入直到文件结束

问题描述

我正在解决一个图形问题,我必须从文件中获取输入。下面是我的input.txt文件。

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

在上面的 input.txt 文件中,第一个输入是没有顶点,直到文件末尾的其他输入是 Graph 的有向边。第一个是源,第二个是目标。所有输入将从 input.txt 文件中读取。

#include <bits/stdc++.h>
#include <fstream>
using namespace std;

class Graph {
    private:        
        int V;
        list<int> *l;

    public:
        Graph(int V) {
            this->V = V;
            l = new list<int>[V];
        }

        void addEdge(int source, int destination) {
            // As it is a directed graph edge will be source to destination only
            l[source].push_back(destination);
        }

        void printAdjList() {
            for(int i = 1; i <= V; i++) {
                cout << "Vertex " << i << "-> " ;
                for(int previous: l[i]) {
                    cout << previous << " " ;
                }
                cout << endl;
            }
        }
};



int main() {
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);

    ifstream inputFile;
    inputFile.open("input.txt");

    int noOfVertex, s, d, noOfEdge=20;
    inputFile >> noOfVertex ;
    // cout << noOfVertex << endl;

    Graph g(noOfEdge);

    // while(cin.eof()) {
    //     // cout << s << " " << d << endl;
    //     cin >> s >> d;
    //     g.addEdge(s, d);
    // }

    if(inputFile) {
        while(inputFile >> s >> d) {
            // cout << s << " " << d << endl;
            g.addEdge(s, d);
        }

        inputFile.close();
    }
    else {
        cout << "Error opening input file" << endl;
    }

    g.printAdjList();

    return 0;
}

运行代码后我得到了这个结果

Vertex 1-> 2 
Vertex 2-> 3 4 5 
Vertex 3-> 6 
Vertex 4-> 5 7 
Vertex 5-> 2 6 7 
Vertex 6-> 3 8 
Vertex 7-> 8 10 
Vertex 8-> 7 
Vertex 9-> 7 
Vertex 10-> 9 11 
Vertex 11-> 12 
Vertex 12-> 10 
Vertex 13-> 
Vertex 14-> 
Vertex 15-> 
Vertex 16-> 
Vertex 17-> 
Vertex 18-> 
Vertex 19-> 

我不能为这个问题取边数。vetices 的数量和给定的有向边将从文件中逐行获取,它将显示类似的邻接列表

Vertex 1-> 2 
Vertex 2-> 3 4 5 
Vertex 3-> 6 
Vertex 4-> 5 7 
Vertex 5-> 2 6 7 
Vertex 6-> 3 8 
Vertex 7-> 8 10 
Vertex 8-> 7 
Vertex 9-> 7 
Vertex 10-> 9 11 
Vertex 11-> 12 
Vertex 12-> 10 

如何从文件中获取输入,以便获得上述输出?我已经应用了很多方法,但没有任何效果。

标签: c++algorithminputgrapheof

解决方案


我建议您使您的 addEdge 方法更灵活且更易于使用。作为一个问题,如果源输入大于列表的大小,您的程序将崩溃。逻辑应该是:

if there is no source vertex, add it
if there is no destination vertex, add it
add link from source to destination.

以下是对建议过程的更详细说明。

/// find vertex "n", returning vertex index, or -1 if missing
 int find( int n )
{
  loop over graph
     if vertex is "n
        return index
  return -1
}

/// find vertex "n", or add it if not present
int findoradd( int n )
{
   int i = find( n );
   if( i >= 0 )
      return i
   return addvertex( n )
}

/// add link between vertices
void addLink( int u, int v )
{
    addEdge(
       findoradd( u ),
       findoradd( v ) );
}

推荐阅读