首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 兩大文本檔去重:目標檔全讀入 unordered_set,源檔逐行查找過濾,O(N) 輕鬆搞定 2 萬行

     編輯:程式設計綜合問答

場景:源檔、目標檔各 2 萬+ 行,每行一個字串 (字段)。需刪除源檔中「已存在於目標檔」的行。

最佳演算法:Hash Set 查找 O(1)

  1. 目標檔全讀入 `std::unordered_set targetSet`;記憶體約 2 萬 × 平均 50 字節 ≈ 1 MB,極小。
  2. 源檔逐行讀取,`if (targetSet.count(line)) continue;` 寫入新檔/覆蓋。
  3. 時間複雜度 O(N+M),N=源檔行數,M=目標檔行數;單機毫秒級完成。

核心代碼 (C++17)

#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;
}

進階優化

  • **超大檔 (GB 級)**:目標檔建 Bloom Filter 降低記憶體,或外部排序 + 歸併去重。
  • **去除空白/大小寫不敏感**:讀入前 `trim` + `tolower` 統一規格化。
  • **保留順序/去重源檔內部重複**:用 `unordered_set` 記錄已寫入行,二次過濾。

2 萬行屬於輕量級,**直接全讀入記憶體最簡單、最快、最不易出錯**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved