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

标签 c++ string graph

我有一个图形文件作为

    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/

相关文章:

Python 将字符串转换为命名空间

C sscanf 和字符串格式

javascript - flot 曲线从第一点开始

ios core plot增加CPTPlotSymbol可点击区域

c++ - section.data 中错误的 reloc 地址 0x0 python 的 C 扩展

C++ 函数指针到类模板静态方法的映射

c++ - 将 32 位整数的 vector 相乘,仅取高 32 位

c++ - 我的 LookAt 的 SSE 实现不起作用

ruby - 从 Ruby 字符串中删除除字母和数字以外的所有字符

c - 试图在 c 中对图进行拓扑排序?