我需要解析這種形式的一個圖形文件:解析圖形文件中使用字符串流C++
5
0 1 0.2 3 10.1 4 0.5 -1
1 0 1.5 -1
2 1 100.0 3 50.2 -1
3 -1
4 1 10.5 2 13.9 -1
當第一線是節點的數量。從第二行開始,
0 1 0.2 3 10.1 4 0.5 -1
0是源節點,1是它前往的節點,0.5是邊的權重。 -1表示行結束。
我創建了一個圖形類:
#ifndef GRAPH_H
#define GRAPH_H
#include <vector>
#include <iostream>
class Graph{
public:
explicit Graph(int size=0) : vertices_(size) { };
void resize(int size){
vertices_.resize(size);
empty();
}
void insert(int v, int n, double w){
Vertex* tmp = new Vertex{ n, w, nullptr }
cout << " inserting!";
end(v)->next = tmp;
}
void empty(){
for(int i=0;i<vertices_.size();i++)
vertices_[i] = new Vertex{i,0,nullptr}
}
void print() {
for(auto& v : vertices_){
Vertex* tmp = v;
cout<< " Node " << v->node << " has edges to: \n"
while(tmp->next != nullptr){
cout<< " node " << tmp->node << " with weight " << tmp->weight<<endl;
}
cout<<endl;
}
}
private:
struct Vertex{ // struct for vertices of graph
int node;
double weight;
Vertex* next;
Vertex (int n, double w, Vertex* v)
: node{ n }, weight{ w }, next{ v } { }
};
vector<Vertex*> vertices_;
Vertex* end(int v){
Vertex* tmp = vertices_[v];
while(tmp->next != nullptr)
tmp = tmp->next;
return tmp;
}
};
#endif
我有這個解析器迄今:(所有的變量是合適的類型)
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <string>
#include "graph.h"
using namespace std;
int main(int argc, char** argv) {
if(argc<3){
cout<<"Usage: " << argv[0] << " <graph file> <starting vertex>\n";
return 0;
}
bool first = true; // true until the first line is read (flow control)
stringstream parse; // stringstream for easy parsing & conversion of strings
int n, s; // holds the nodes for inserting
double w; // holds the weights for edges
string line;
ifstream graph1(argv[1]);
Graph g;
while(getline(graph1,line)){
if(first){
n=stoi(line);
g.resize(n);
first = false;
} else {
parse << line;
first = true;
while(getline(parse,line,' ')&&line != "-1"){
if(first){
parse >> s;
g.insert(s,s,0)
first = false;
}
parse >> n >> w;
cout << s << " " << n << " " << w <<endl;
g.insert(s,n,w);
}
}
}
但是當我print()
我得到一個賽格故障。我究竟做錯了什麼?
你能告訴我們你的解析函數的其餘部分嗎? – refi64
'\t bool first = true; \t \t \t stringstream parse; \t \t \t int n,s; \t \t \t \t \t double w; \t \t \t \t \t string line; \t \t \t \t ifstream graph1(argv [1]); \t圖g;' – zeta
你能用該代碼編輯你的問題嗎? – refi64