如何在两个文件 C++ 中找到相同的行?
How do I find same lines in two files C++?
我需要为我的学校项目编写一个程序,比较来自两个大文件的行,一个大约。 1.5G(40kk 线),另一个是大约。 5gb(100kk 行)查找重复行并将这些行写入新文件。
我已经尝试在 NodeJs 和 Python 中编写这些程序,但是,他们无法比较这些文件,Python 看起来只比较一行需要 30 分钟.也许我做错了什么。
我想知道 C++ 是否能够轻松处理这个任务,比较这些文件的最快方法是什么,有什么建议吗?
你有多种选择来解决这个问题,none 其中很漂亮。
我相信,更有效的选择之一是这样的:
#include <iostream>
#include <fstream>
#include <map>
int main()
{
std::ifstream firstFile("firstFile");
std::ifstream secondFile("secondFile");
if (firstFile.is_open() && secondFile.is_open())
{
std::string line;
while(!secondFile.eof())
{
std::map<std::string, bool> stringMap;
for (int i = 0;
i < 500000 &&
!std::getline(secondFile, line).eof();
++i
)
stringMap[line] = false;
while (!std::getline(firstFile, line).eof())
{
std::map<std::string, bool>::iterator it = stringMap.find(line);
if (it != stringMap.end())
it->second = true;
}
firstFile.clear(); //Clears the eof Flag.
firstFile.seekg(0); //Rewinds to the beginning of the list.
//Iterate over map and write all matches to the result file
}
}
return 0;
}
此(有点伪)代码将以 50 万行的块读取第二个文件,对第一个文件的所有行执行检查,并为您提供两个文件中所有行的列表。
虽然完全未经测试。
我需要为我的学校项目编写一个程序,比较来自两个大文件的行,一个大约。 1.5G(40kk 线),另一个是大约。 5gb(100kk 行)查找重复行并将这些行写入新文件。
我已经尝试在 NodeJs 和 Python 中编写这些程序,但是,他们无法比较这些文件,Python 看起来只比较一行需要 30 分钟.也许我做错了什么。
我想知道 C++ 是否能够轻松处理这个任务,比较这些文件的最快方法是什么,有什么建议吗?
你有多种选择来解决这个问题,none 其中很漂亮。
我相信,更有效的选择之一是这样的:
#include <iostream>
#include <fstream>
#include <map>
int main()
{
std::ifstream firstFile("firstFile");
std::ifstream secondFile("secondFile");
if (firstFile.is_open() && secondFile.is_open())
{
std::string line;
while(!secondFile.eof())
{
std::map<std::string, bool> stringMap;
for (int i = 0;
i < 500000 &&
!std::getline(secondFile, line).eof();
++i
)
stringMap[line] = false;
while (!std::getline(firstFile, line).eof())
{
std::map<std::string, bool>::iterator it = stringMap.find(line);
if (it != stringMap.end())
it->second = true;
}
firstFile.clear(); //Clears the eof Flag.
firstFile.seekg(0); //Rewinds to the beginning of the list.
//Iterate over map and write all matches to the result file
}
}
return 0;
}
此(有点伪)代码将以 50 万行的块读取第二个文件,对第一个文件的所有行执行检查,并为您提供两个文件中所有行的列表。
虽然完全未经测试。