分割字符串作为邻接矩阵索引
splitting a string as an adjacency matrix index
我有一个图形文件
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;
相关文章:
- 如何在C++中为表面制作邻接矩阵
- 在 c++ 中初始化邻接矩阵
- 如何对存储为"Compressed Sparse Row"的矩阵进行稀疏矩阵索引?
- 有关邻接矩阵实现的问题
- MFC:在编辑框中表示邻接矩阵
- C++中有向无环图的邻接列表到邻接矩阵的转换
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 如何正确接受平方加权邻接矩阵
- 创建随机邻接矩阵,每个节点具有最小'k'度
- 如何在C++中将边列表转换为邻接矩阵,其中包含连接到顶点的边数而不是一条边?
- 确定邻接矩阵是否具有周期,然后输出该周期
- 邻接矩阵构建功能用一些图崩溃
- 使用邻接矩阵获取给定节点的所有边缘
- 对邻接矩阵最大循环中的节点进行计数
- 获取 CUDA 设备中的原始矩阵索引
- 图实现,使用邻接矩阵,在链接中带有自定义数据
- 在C++中向邻接矩阵的边添加代价
- 邻接矩阵上的BFS
- 查找路径的有向图邻接矩阵
- 分割字符串作为邻接矩阵索引