将字符串拆分为邻接矩阵索引

时间:2011-12-25 07:56:54

标签: c++ string graph

我有一个图形文件

    3200
    12 16
    114 61
    37 465
    .
    .
    .

and it goes like this.

第一个数字是vertexNumber,其他整数表示顶点,我们之间有一条边。例如myMatrix[12][16] = 1 and myMatrix[16][12] = 1

我使用ifstream读取graph.txt(ifstream theGraphFile("graph.txt", ios::in);)并创建了一个像10000这样的常量大小的bool矩阵

我的目的是:

while( getline( theGraphFile, line ) )
{
        if (line[1])
            continue;
        else
        {
            //parse
            //matrix
        }

}

所以我的问题是:如何将这些数字分隔为“在空格之前直到行尾”格式。如果我在第n行的字符串是12 51我想将它们用作矩阵索引,如myMatrix[12][51] = 1

谢谢.. :))

2 个答案:

答案 0 :(得分:0)

试试此代码

int a = 0, b = -1; 
bool done = false;
for (int i = 0; !done; ++i)
{
  if (line[i] >= '0' && line[i] <= '9')
  {
     if (b == -1)
     {
       a *= 10;
       a += line[i] - '0';
     }
     else
     {
       b *= 10;
       b += line[i] - '0';
     }

  } 
  else if (b == -1)
    b = 0;
  else
    done = true;
}

myMatrix[a][b] = myMatrix[b][a] = 1;

答案 1 :(得分:0)

可以想到两种方式:您可以直接使用ifstream格式化的提取operator >>,或者使用getline将整行放入字符串中,然后使用istringstream将其提取到索引中。

如果您的图形文件一个接一个地包含索引,就像您的示例一样,第一种方法可能会更容易:

while(theGraphFile >> x >> y)
{
    if(x < myWidth && y < myHeight)
        myMatrix[x][y] = true;
}

如果每一行都有其他信息,那么使用getline的第二种方法将允许一些灵活性:

while(getline(theGraphFile, line))
{
    istringstream linestr(line);
    // lines that don't start with x, y indices get skipped.
    // feel free to handle this differently
    if(!(linestr >> x >> y)) continue;  

    if(x < myWidth && y < myHeight) { myMatrix[x][y] = true; }
    // parse other data
}
相关问题