c++有效地跳过多行

C++ skip multiple lines efficiently

本文关键字:有效地 c++      更新时间:2023-10-16

我有代码读取每四行,并对它做一些事情

ifstream in(inputFile, ios::in);
string zeile;
for (int z = 0; z < numberOfSequences; z++) {
    getline(in,zeile); // skip 3 lines
    getline(in,zeile); // skip 3 lines
    getline(in,zeile); // skip 3 lines
    getline(in,zeile);
    // do something with zeile
}

我的问题是,ASCII文件有超过250 000 000行。所以我感兴趣的是跳过3行的最有效方法。getline是否将in解析为字符串,或者这是最有效的方法?我不想浪费时间在跳绳上。

这几乎是最有效的方法;唯一发生的"解析"是搜索您确实需要的行尾。

你唯一可以改进的是不要不必要地存储比你实际要处理的多四倍的行。你可以用std::basic_istream::ignore:

std::ifstream in(inputFile, std::ios::in);
for (int z = 0; in && z < numberOfSequences; z++) {
   // Skip three lines
   for (int i = 0; i < 3; i++)
      in.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
   // Read the fourth line...
   std::string zeile;
   if (std::getline(in, zeile))
      foo(zeile);
}