c ++自定义文本代码输入解析器

时间:2013-05-02 07:10:47

标签: c++ parsing graph matrix

我需要编写一个图形文件解析器(该图由TGFF生成,作为基于标识符/变量的文本文件)

@TASK_GRAPH 0 {
PERIOD 1100

TASK t0_0   TYPE 13 
TASK t0_1   TYPE 3 
TASK t0_2   TYPE 10 
    .
    .

ARC a0_0    FROM t0_0  TO  t0_1 TYPE 9
ARC a0_1    FROM t0_1  TO  t0_2 TYPE 0
ARC a0_2    FROM t0_2  TO  t0_3 TYPE 37
    .
    .
}

#------------------------------------------------------------------------------
# type    exec_time
  0      71.659
  1     59.3856
  2     64.7101
到目前为止,这是迄今为止的iv(不介意碎片代码......这只是一个例子,到目前为止iv是如何完成的)

void read(char* graph){
     //open task graph description
     string name;
     string TaskList[300][300];
     ifstream gfile;
     gfile.open (graph);
     if ( !gfile.is_open() ) cout<<"Could not open graph description file\n";
     //start parsing
     while(getline(gfile,inptext)){
        istringstream sstream(inptext);
        int i=0;
        sstream >> name;
        if(name.compare("TASK")==0){
            sstream >> name;i
            //wrte node name to hash index i++
            sstream >> name;
            if (name.compare("TYPE")==0){
                sstream >> name;
                //retrieve node index from hash
                //write node weight to matrix
            }
        }
        if(name.compare("ARC")==0){
           sstream >> name;
           //write edge name to hash index i++
           sstream >> name;
           if (name.compare("FROM")==0){
              sstream >> name;
              //retrieve node index a from hash
           }
            sstream >> name;
            if (name.compare("TO")==0){
              sstream >> name;
              //retrieve node index b from hash
              if (name.compare("TYPE")==0){
                sstream >> name;
                //write edge weight to matrix index a b
              }
            }
         }
        i++;
     }
     //end parsing
     gfile.close();
 }

因为在我不打扰阅读之前我没有使用过令牌。现在我遇到的问题是文件底部的TYPE值的读取周期,因为它们的标识符是常规数字,并且您无法使它们成为要搜索的标识符。我猜测最好的方法是寻找“#type”但是因为我正在使用字符串流,所以有点难以应对。第二个问题是节点的数量事先是未知的,所以我无法初始化数组矩阵以适应图形的大小......

我应该:

  • a)读取文件两次 - 一次计算节点,其他时间实际读取数据
  • b)使用矢量/矩阵类型(我之前没有使用过,我认为我必须构建一个矩阵类)
  • c)使用别的东西

我想的矩阵应该是 matrix [x] [x]其中n是节点权重,e是边缘权重(由于边缘只有一个方向是未镜像的)到目前为止我计划用类型编号填充矩阵并稍后从哈希或向量中读取类型用正确的值替换它们

  A B C D E
A n 0 0 0 0
B e n 0 0 0
C e e n 0 0
D e e e n 0
E e e e e n

如果有人知道如何更轻松地阅读和解析这个文件,那就太棒了。

1 个答案:

答案 0 :(得分:1)

为解决将任务名称映射到标识符的问题,例如将t0_0映射到0, t0_1到1以及处理节点名称的其他格式,我建议使用任务名称作为键和矩阵索引作为值的哈希表。

以下函数将返回给定任务名称的索引。如果第一次满足任务名称,它将创建一个新索引,将其分配给任务名称并返回该名称。

#include <unordered_map>
int tasks = 0;
std::unordered_map<std::string, int> hashNameToIndex;

int nameToIndex(string name){    
  if (hashNameToIndex.find(name) == hashNameToIndex.end()){
     hashNameToIndex[name] = tasks;
     tasks++;
     return tasks-1;
  }else{
     return hashNameToIndex[name];
  }
}