1 void Graph::InputListGene(bool TOG,int nbNodes,ifstream& f){ 2 string* line = new string[nbNodes]; 3 int count =0; 4 while(!f.eof()){ 5 getline(f,line[count],';'); 6 count++; 7 } 8 for(int i=0;i<count;i++){ 9 Vertex *v = new Vertex(i);// to initialize 10 v->color = 0; //O black & 1 white 11 listVertex.push_back(v); 12 } 13 int p=0; 14 regex pattern_node("\\d+,\\d+"); 15 for(int i=0;i<count;i++){ 16 17 for(sregex_iterator it(line[i].begin(),line[i].end(),pattern_node),end;it!=end;it++){ 18 char *cstr = new char[it->str().size()+1]; 19 char delim[]=",";//splitter of the numbers 20 int dest,weight; 21 strcpy(cstr,it->str().c_str());//convert string to char 22 dest = atoi(strtok(cstr,delim)); 23 weight = atoi(strtok(NULL,delim)); 24 Vertex *v = new Vertex(dest);// to initialize 25 v->color = 0; //O black & 1 white 26 listVertex.push_back(v); 27 cout<<dest<<" "<<weight<<" "; 28 Edge *e = new Edge(p, listVertex[i],listVertex[dest],weight); 29 } 30 cout<<endl; 31 } 32 } 33 // in file "Graph.cpp"
這是Graph.cpp文件其中的一個函數,用於從txt文件中讀取有向圖的信息,並生成數據結構。
相關數據類型的定義:
11和26行之前碰到了was not declared in this scope 的問題,一開始很疑惑,在開頭寫了#include "Graph.h" ,而在Graph.h 文件中的類Graph中有public成員Vector<Vertex*> listVertex 。本以為用了include就能訪問類成員。這里犯了一個低級錯誤。首先需要把函數聲明為類的成員函數,然后在定義函數時在函數名前加上操作域解析符Graph:: 這樣才能在函數中訪問類的成員。
另外,這個函數還實現了從txt文件中讀取指定格式的數字並分別截取的辦法。
假設txt文件如下:
圖的結構如下:
首先截取前3行的數據,第一行代表頂點個數,第二行有向(o)還是無向圖(n);第三行表示鄰接矩陣(m)還是鄰接鏈表(l)。
然后在下一個函數中處理其后的具體數據:
將文件流作為參數傳入,在這個函數中再getline()就是從文件的第四行開始了。geline把以分號結尾的每一行數據讀入line數組中。
首先,regex表示以逗號隔開的一個數對。這里用到了一個正則表達式迭代器sregex_iterator來遍歷每一行數據,一開始的這個s表示這是一個作用於string類上的正則表達式迭代器。至於for里面的神奇寫法,我好像也是從別處模仿來的,總之迭代器作用於當前line[]之上。
it->str()應該就是匹配到的每一個數對(如:2,5)。strtok()函數只能處理char類型,於是先把這個數對由string轉換到char,再對其用定義好的分隔符';'進行切割。得到的數對的第一個數就是指向的下一個鄰接結點的編號;第二個便是這條邊的權值。