读取包含int的字符串到数组的最快方法是什么?

what is the fastest way to read strings contating int to an array

本文关键字:方法 是什么 包含 int 字符串 读取 数组      更新时间:2023-10-16

我有一个包含数字字符串的文件,如下所示:

1 2
10 22
123 0
125 87

我想把它读入一个two dim数组所以我有

lut[0]={1,2};
lut[1]={10,22};
lut[2]={123,0};
lut[3]={125,87};

在c++中最快的方法是什么

与处理器计算相比,任何文件输入/输出都是缓慢的。所以你可以用任何你想要的方式解析文件。运行时间将接近文件输入操作的时间。

代码示例

Ideone

#include <fstream>
const static int N = 1000;
int main()
{
    int lut[N][2];
    std::ifstream f("input_file.txt");
    int index = 0;
    while(!f.eof())
    {
        int l1 = 0;
        int l2 = 0;
        f >> l1 >> l2;
        lut[index][0] = l1;
        lut[index][1] = l2;
        ++index;
        if (index == N)
            break; // WARN
    }
    return 0;
}