分割字符串作为邻接矩阵索引

splitting a string as an adjacency matrix index

本文关键字:邻接矩阵 索引 字符串 分割      更新时间:2023-10-16

我有一个图形文件

    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);),并创建了一个常量大小的bool矩阵,如10000

我的模式是这样的:

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

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

谢谢. .:)

我想到了两种方法:你可以直接从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
}

试试这个代码

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;