場景:源檔、目標檔各 2 萬+ 行,每行一個字串 (字段)。需刪除源檔中「已存在於目標檔」的行。
#include
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
unordered_set target;
string line;
ifstream fin_target("target.txt");
while (getline(fin_target, line)) target.insert(line);
fin_target.close();
ifstream fin_source("source.txt");
ofstream fout("source_filtered.txt");
while (getline(fin_source, line)) {
if (!target.count(line)) fout << line << '\n';
}
// 如需原地覆蓋:rename("source_filtered.txt", "source.txt");
return 0;
}
2 萬行屬於輕量級,**直接全讀入記憶體最簡單、最快、最不易出錯**。