我有很多txt檔案,大約10GB。我應該在我的程式中使用什么來將它們合并到一個沒有重復的檔案中?我想確保輸出檔案中的每一行都是唯一的。
我正在考慮制作某種哈希樹并使用 MPI。我希望它有效。
uj5u.com熱心網友回復:
- 建立一個檔案表,這樣你就可以簡單地給每個檔案名一個數字(一個
std::vector<std::string>很好用)。 - 對于表中的每個檔案:打開它,執行以下操作:
- 讀一行。散列線。
- 有一個
std::map將行哈希(步驟 3)映射到std::pair<uint32_t filenumber, size_t byte_start_of_line>. 如果你的新行哈希已經在哈希表中,打開指定檔案,seek到指定位置,并檢查你的新行和舊行是否相同或只是共享相同的哈希。 - 如果相同,跳過;如果不同或尚不存在:向映射添加新條目,將行寫入輸出檔案
- 閱讀下一行(即,轉到第 3 步)
這只需要最長行所需的 RAM,加上足夠的 RAM 用于檔案名 檔案號加上開銷,加上映射空間,這應該遠遠小于實際行。由于 10GB 并不是很多文本,因此發生哈希沖突的可能性相對較小,因此如果您不確定,則最好跳過“檢查現有檔案”部分,但所有行的概率都足夠高在你的輸出中。
uj5u.com熱心網友回復:
如果您沒有要求保持低記憶體使用率,您可以將所有檔案中的所有行讀入 a std::setor std::unordered_set。An unordered_setis 顧名思義,沒有以任何特定方式排序,而 a setis(字典排序順序)。我在std::set這里選擇了 a ,但您可以嘗試使用 astd::unordered_set來查看是否可以加快速度。
例子:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <string_view>
#include <vector>
int cppmain(std::string_view program, std::vector<std::string_view> args) {
if(args.empty()) {
std::cerr << "USAGE: " << program << " files...\n";
return 1;
}
std::set<std::string> result; // to store all the unique lines
// loop over all the filenames the user supplied
for(auto& filename : args) {
// try to open the file
if(std::ifstream ifs(filename.data()); ifs) {
std::string line;
// read all lines and put them in the set:
while(std::getline(ifs, line)) result.insert(line);
} else {
std::cerr << filename << ": " << std::strerror(errno) << '\n';
return 1;
}
}
for(auto line : result) {
// ... manipulate the unique line here ...
std::cout << line << '\n'; // and print the result
}
return 0;
}
int main(int argc, char* argv[]) {
return cppmain(argv[0], {argv 1, argv argc});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321234.html
下一篇:為什么這個程式有邏輯錯誤
