gpt4 book ai didi

c++读取文件太慢

转载 作者:太空狗 更新时间:2023-10-29 20:22:42 27 4
gpt4 key购买 nike

我正在尝试读取 ~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();

如有任何帮助,我们将不胜感激。

最佳答案

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

结果是您的 line_stream 累积所有先前的行,并且内部循环将一次又一次地在所有累积的行上运行单词。

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

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

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();

关于c++读取文件太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36613731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com