这可能是一个非常愚蠢的问题,但我如何优化这段代码以使其更高效(更快、内存消耗更少)?我制作这段代码是为了帮助我对一些文本文件进行排序。它从第一个文件中读取每个字符串,然后搜索第二个文件,直到找到所有相关字符串,然后在第三个文件中写入一些匹配的字符串。这是代码:
ifstream h("SecondFile.txt");
ifstream h2("FirstFile.txt");
ifstream uh("MatchedStrings.txt");
ofstream g("sorted.txt");
int main()
{
string x, y, z;
cout << "Sorting..." << endl;;
while (!h.eof()){
h >> x;
while (!h2.eof() || (y == x)){
h2 >> y;
uh >> z;
if (y == x){
g << z << endl;
break;
h2.clear();
h2.seekg(0);
uh.clear();
uh.seekg(0);
}
}
if (h2.eof() && (y != x)){
g << "none" << endl;
h2.clear();
h2.seekg(0);
uh.clear();
uh.seekg(0);
}
}
cout << "Finished!";
}
我已将我的代码更改为:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream h("SecondFile.txt");
ifstream h2("FirstFile.txt");
ifstream uh("MatchedStrings.txt");
ofstream g("sorted.txt");
int main()
{
string x;
bool write_none = true;
int i = 0,l=0;
string check[] = {""};
string unhashed_checked[] = { "" };
string sorted_array[] = { "" };
cout << "Sorting..." << endl;
//Get to memory
while (!h2.eof())
{
h2 >> check[i];
uh >> unhashed_checked[i];
i++;
}
while (!h.eof()){
h >> x;
write_none = true;
for (int t = 0; t <= i;t++)
{
if (x == check[t])
{
break;
write_none = false;
sorted_array[l] = unhashed_checked[i];
l++;
}
}
if (write_none)
{
sorted_array[l] = "none";
l++;
}
}
for (int k = 0; k <= l; k++)
{
g << sorted_array[k]<<endl;
}
cout << "Finished!";
}
但是我在运行程序时遇到了这个异常:
Unhandled exception at 0x01068FF6 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC
最佳答案
将 h
加载到字符串 vector 中,并通过将每个字符串与 vector 的内容进行比较来遍历 h2
一次。
由于您的测试是对称的,您可以选择 h
作为两个文件中最小的一个。这样,您将节省内存和时间,尤其是当其中一个文件比另一个文件大得多时。如果比较需要花费大量时间,使用集合 (std::set
) 代替 vector 也会有所帮助。
关于c++ - 优化 .txt 文件中的字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962405/