优化.txt文件中的字符串搜索
Optimize string search in .txt file
这可能是
一个非常愚蠢的问题,但是我如何优化此代码以使其更有效(更快,更少的内存消耗)?我制作了这段代码来帮助我对一些文本文件进行排序。它从第一个文件中读取每个字符串,然后搜索第二个文件,直到找到所有相关字符串,并在第三个文件中写入一些匹配的字符串。这是代码:
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
)代替向量在比较花费大量时间的情况下也会有所帮助。
假设文件中的字符串数分别为 n 和 m。
按照你现在的做法,复杂度是Θ(n m)。此外,复杂性常数是文件操作的常数,非常慢。
相反,您应该只将其中一个文件读入std::unordered_*
容器,然后比较容器之间的键。这应该将运行时间减少到预期的 Θ(n + m)。
作为旁注,您可能希望查看将字符串读取到容器中的更现代方法(例如,使用 std::istream_iterator
)。
相关文章:
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- 有序地图字符串搜索与整数搜索之间的时间复杂度
- 使用图形的字符串搜索算法?C++
- C++子字符串搜索 - 跳入C++
- 字符串搜索 - 并行版本较慢
- 使用Robert Sedwick书中的符号表进行字符串搜索
- C++中的部分字符串搜索
- 哪个是更好的字符串搜索算法?Boyer-Moore或Boyer Moore Horspool
- 如何使用 c++ 将字符串搜索到字符串数组中
- 使用 C++ 在文件中进行字符串搜索/索引
- Qt5 中字符串搜索的最佳容器
- 优化.txt文件中的字符串搜索
- 字符串搜索输入中包含的单词
- Boyer-Moore-坏字符规则实现子字符串搜索
- 带星号*通配符的字符串搜索
- c++字符串搜索函数
- 最好的字符串搜索算法
- 通配符字符串搜索算法
- 在c++中使用字符串(搜索字符串,分割字符串,cout<<字符串)
- Strstr()函数重叠字符串搜索