【问题标题】:Reading graph from stream to vector of adjacency list从流中读取图形到邻接表的向量
【发布时间】:2020-01-31 09:47:06
【问题描述】:

我正在尝试通过读取下面显示的文件来创建一个图形作为邻接列表

这里的第一行是顶点数。在下面的示例中,我们有 12 个顶点,并且在以下行中 例如 1 2 3 4 表示顶点 1 的边为 2、3 和 4。

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

C++ 程序

#include <iostream>
#include <fstream>
#include <strstream>
#include <sstream> // for std::getline

#include "Graph.h"

using namespace std;

// Note: vector index is will match the vertex id.
std::vector <std::vector<std::pair<int, int> > > vecIdxedGraph;


void storeEdges(const string& strEdges) {
    std::istringstream iss(strEdges);
    int FromVertex = 0;
    iss >> FromVertex;

    std::cout << "From Vertex " << FromVertex << endl;

    vector<pair<int, int>> edges;
    string toVertex;
    while (std::getline(iss, toVertex, ' ')) {
        std::cout << "to Vertex " << toVertex << " ";
        edges.push_back(std::make_pair(atoi(toVertex.c_str()), 0));
    }
    std::cout << std::endl;
    vecIdxedGraph.push_back(edges);
    return;
}

void printGraph() {
    for (int i = 0; i < vecIdxedGraph.size(); i++) {
        cout << "Vertex " << i + 1 << " ";
        for (int j = 0; j < vecIdxedGraph[i].size(); j++) {
            cout << vecIdxedGraph[i][j].first << " ";
        }
        cout << endl;
    }
}
int main() {

    // create Graph
    ifstream inFile("Graph.txt");
    if (!inFile) {
        cout << "Open input file failed." << endl;
    }

    // Set input stream to file.
    std::streambuf* pOldCinBuf = cin.rdbuf();
    cin.set_rdbuf(inFile.rdbuf());

    int iNumberOfNodes;
    cin >> iNumberOfNodes;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Number of nodes in graph are: " << iNumberOfNodes << endl;

    vecIdxedGraph.reserve(iNumberOfNodes);



    for (int iVertexId = 1; iVertexId <= iNumberOfNodes; iVertexId++) {
        std::string vertIdDetails;
        std::getline(cin, vertIdDetails);
        // cout << (vertIdDetails.c_str()) << endl;
        // parse line and store to the vector.
        storeEdges(vertIdDetails);
        // cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    printGraph();
    return 0;
}

下面是输出

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

想要删除 0。我认为 0 在读取一行时来自空白空间

while (std::getline(iss, toVertex, ' '))

我不知道如何清除它。

另一个问题是如何创建一个默认构造的向量以便我可以使用

vecIdxedGraph[FromVertex] = ...,而不是 push_back。

请帮忙

【问题讨论】:

  • 您不使用&gt;&gt; 阅读其余行的任何特殊原因?
  • @Botje 因为我们不知道每个顶点有多少条边。
  • 所以请继续调用&gt;&gt;,直到iss.eof() 为真
  • 如果你有“零来自空白”之类的怀疑,那你为什么不自己验证呢?比如在while 的开头添加一点cout &lt;&lt; toVertex &lt;&lt; endl;?此外,所有这些确实应该是一个适当的类,甚至两个(GraphGraph::Vertex)。帮助您模块化并定位错误。您的主要内容应类似于Graph graph(file); graph.print();。而全局变量是一件坏事。

标签: c++ vector data-structures graph


【解决方案1】:

看起来你在这里把事情复杂化了。您只需要以下内容。

// Some handy names
using Pair = std::pair<int, int>;
using Graph = std::vector<std::vector<Pair>> ;

// The stream handle
std::ifstream fileHandle("Graph.txt");

size_t iNumberOfNodes  = 0;

// 1. Get # of Vertices
fileHandle >> iNumberOfNodes;

// 2. Create a graph, pre allocate the # of vertices
// One node extra since your vertices starts from 1
Graph g{iNumberOfNodes + 1, std::vector<Pair>{}}; 

std::string lineStr;
int currNode = 0, vertex;
// 3. Iterate over file, reading line by line
while ( std::getline(fileHandle, lineStr) ) {
   std::stringstream ss{lineStr};
    ss >> currNode;
    while ( currNode != 0 && ss >> vertex ) {
        g[currNode].emplace_back( vertex, 0 ) ; // weight = 0;
    }   
 }

一切就绪! Demo Here

【讨论】:

  • @POW 谢谢。为什么我们在下面的行中使用 emplace_back 而不是 push_back。 g[currNode].emplace_back( 顶点, 0 )
  • @venkysmarty This 将回答问题
猜你喜欢
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多