C++中"was not declared in this scope"问题记录;以及通过正则表达式提取文件中数字的方法

 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,再对其用定义好的分隔符';'进行切割。得到的数对的第一个数就是指向的下一个邻接结点的编号;第二个便是这条边的权值。 

posted @ 2019-11-15 05:38  略略略——  阅读(6980)  评论(0编辑  收藏  举报