c ++读取文件太慢了

Lig*_*XXV 3 c++ stream

我试图阅读~36KB,完成这个循环需要大约20秒:

ifstream input_file;

input_file.open("text.txt");
if( !(input_file.is_open()) )
{
    cout<<"File not found";
    exit(1);
}

std::string line;
stringstream line_stream;   //to use << operator to get words from lines

int lineNum=1;

while( getline(input_file,line) )   //Read file line by line until file ends
{
    line_stream.clear();    //clear stream
    line_stream << line;    //read line
    while(line_stream >> word)  //Read the line word by word until the line ends
    {
        //insert word into a linked list...
    }
    lineNum++;
}
input_file.close();
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

ZHA*_*kai 6

stringstream::clear()不清楚其中的所有上下文.它只重置错误和EOF标志,请参阅http://en.cppreference.com/w/cpp/io/basic_ios/clear.

结果是你line_stream累积了所有前面的行,内部循环将一次又一次地在所有累积的行上运行单词.

因此,您花费的总时间约为O(n ^ 2),而O(n)则与您预期的相比.

您可以line_stream在while循环中定义新实例,而不是在每一行中使用相同的对象,以获得全新且空的实例.像这样:

fstream input_file;

input_file.open("text.txt");
if( !(input_file.is_open()) )
{
    cout<<"File not found";
    exit(1);
}

std::string line;

int lineNum=1;

while( getline(input_file,line) )   //Read file line by line until file ends
{
    stringstream line_stream;   // new instance, empty line.
    line_stream << line;    //read line
    while(line_stream >> word)  //Read the line word by word until the line ends
    {
        //insert word into a linked list...
    }
    lineNum++;
}
input_file.close();
Run Code Online (Sandbox Code Playgroud)

  • 另一种重置字符串流的简洁方法:`line_stream.str(std :: string());` (2认同)
  • 因此,您可以使用`line_stream.str(line);`重置流,并跳过`<<`插入. (2认同)