我有一个图形文件作为
3200
12 16
114 61
37 465
.
.
.
and it goes like this.
第一个数字是 vertexNumber 其他整数代表顶点,我们在它们之间有一条边。例如 myMatrix[12][16] = 1 和 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
谢谢..:)
最佳答案
想到2种方法:可以直接使用ifstream的格式化提取operator >>
,也可以先用getline把整行变成一个字符串,然后用istringstream提取成indices。
如果您的图形文件只包含一个接一个的索引,就像您的示例一样,第一种方法可能会更简单:
while(theGraphFile >> x >> y)
{
if(x < myWidth && y < myHeight)
myMatrix[x][y] = true;
}
如果每一行也有其他信息,第二种方法 getline 将允许一些灵 active :
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
}
关于c++ - 将字符串拆分为邻接矩阵索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8628754/