优化.txt文件中的字符串搜索

Optimize string search in .txt file

本文关键字:字符串 搜索 txt 文件 优化      更新时间:2023-10-16
这可能是

一个非常愚蠢的问题,但是我如何优化此代码以使其更有效(更快,更少的内存消耗)?我制作了这段代码来帮助我对一些文本文件进行排序。它从第一个文件中读取每个字符串,然后搜索第二个文件,直到找到所有相关字符串,并在第三个文件中写入一些匹配的字符串。这是代码:

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,并通过将每个字符串与向量的内容进行比较来循环h2一次。

由于测试是对称的,因此可以选择h作为两个文件中最小的一个。这样,您将节省内存和时间,特别是如果其中一个文件比另一个文件大得多。使用集合(std::set)代替向量在比较花费大量时间的情况下也会有所帮助。

假设文件中的字符串数分别为 nm

按照你现在的做法,复杂度是Θ(n m)。此外,复杂性常数是文件操作的常数,非常慢。

相反,您应该只将其中一个文件读入std::unordered_*容器,然后比较容器之间的键。这应该将运行时间减少到预期的 Θ(n + m)。


作为旁注,您可能希望查看将字符串读取到容器中的更现代方法(例如,使用 std::istream_iterator )。