我目前正在开发一个小程序来连接两个文本文件(类似于数据库连接)。一个文件可能如下所示:
269ED3
86356D
818858
5C8ABB
531810
38066C
7485C5
948FD4
第二个类似:
hsdf87347
7485C5
rhdff
23487
948FD4
两个文件都超过 1.000.000 行,并且不限于特定的字符数。我想做的是在两个文件中找到所有匹配的行。
我已经尝试了一些东西,数组、 vector 、列表 - 但我目前正在努力决定什么是最好的(最快的和内存简单的)方法。
我的代码目前看起来像:
#include iostream>
#include fstream>
#include string>
#include ctime>
#include list>
#include algorithm>
#include iterator>
using namespace std;
int main()
{
string line;
clock_t startTime = clock();
list data;
//read first file
ifstream myfile ("test.txt");
if (myfile.is_open())
{
for(line; getline(myfile, line);/**/){
data.push_back(line);
}
myfile.close();
}
list data2;
//read second file
ifstream myfile2 ("test2.txt");
if (myfile2.is_open())
{
for(line; getline(myfile2, line);/**/){
data2.push_back(line);
}
myfile2.close();
}
else cout data2[k], k++
//if data[j] > a;
return 0;
}
我的想法是:使用 vector 时,随机访问元素非常困难,跳转到下一个元素也不是最优的(代码中没有,但我希望你能明白这一点)。使用 push_back 并逐行添加将文件读入 vector 也需要很长时间。使用数组,随机访问更容易,但是将 >1.000.000 条记录读取到数组中将非常占用内存并且也需要很长时间。列表可以更快地读取文件,随机访问又很昂贵。
最终我不仅会查找完全匹配项,还会查找每行的前 4 个字符。
你能帮我决定,最有效的方法是什么吗?我尝试过数组、 vector 和列表,但对目前的速度不满意。还有其他我没有考虑过的查找匹配项的方法吗?我很高兴完全更改代码,期待任何建议!
非常感谢!
编辑:输出应该列出匹配的值/行。在此示例中,输出应该如下所示:
7485C5
948FD4
最佳答案
读取 200 万行不会太慢,可能会变慢的是您的比较逻辑:
data1.sort(data1.begin(), data1.end()); // N1log(N1)
data2.sort(data2.begin(), data2.end()); // N2log(N2)
std::vector<int> v; //Gives the matching elements
std::set_intersection(data1.begin(), data1.end(),
data2.begin(), data2.end(),
std::back_inserter(v));
// Does 2(N1+N2-1) comparisons (worst case)
您也可以尝试使用 std::set
并从两个文件中插入行,结果集将只有唯一元素。
关于C++ 将文件读入数组/列表/vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19285985/