首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C++單詞統計程式實作:Set與Map應用

     編輯:關於C

文字檔案單詞統計完整實作

使用 C++ STL 容器 set 與 map 實作單詞去重統計與詞頻計數,展示標準庫演算法在文字處理中的實際應用。

核心類別設計

CWord:單詞封裝類別

class CWord {
    string word;
public:
    CWord(string w) : word(w) {}
    string GetWord() const { return word; }
    
    // 用於 set 排序與去重
    bool operator<(const CWord& w) const { 
        return word < w.GetWord(); 
    }
    
    // 用於 map 查找比較
    bool operator==(const string& s) const { 
        return word == s; 
    }
};

CWordSet:單詞集合(去重)

class CWordSet {
    set<CWord> wordSet;
public:
    bool AddString(string s) {
        wordSet.insert(CWord(s));
        return true;
    }
    
    void show(ostream& os) {
        for (auto it = wordSet.begin(); it != wordSet.end(); ++it)
            os << (*it).GetWord() << "\t";
    }
};

CWordMap:單詞詞頻統計

class CWordMap {
    map<CWord, int> wordMap;
public:
    bool AddString(string s) {
        auto it = wordMap.find(s);
        if (it == wordMap.end())
            wordMap.insert({CWord(s), 1});
        else
            (*it).second++;
        return true;
    }
    
    void Show(ostream& os) {
        for (auto it = wordMap.begin(); it != wordMap.end(); ++it) {
            string ss = (*it).first.GetWord();
            int n = (*it).second;
            os << ss << "\t" << n << endl;
        }
    }
};

主程式流程

int main() {
    CWordSet wordSet;
    CWordMap wordMap;
    
    ifstream in("a.txt");
    string s, delimset = ",.";
    
    while (getline(in, s)) {
        if (s.empty()) continue;
        
        // 標點符號替換為空白
        for (size_t pos = 0; 
             (pos = s.find_first_of(delimset, pos)) != string::npos; 
             ++pos)
            s.replace(pos, 1, " ");
        
        // 字串流分割單詞
        istringstream ss(s);
        while (ss >> s) {
            if (!s.empty()) {
                wordSet.AddString(s);
                wordMap.AddString(s);
            }
        }
    }
    
    cout << "單詞集合為" << endl;
    wordSet.show(cout);
    cout << endl << "單詞及出現次數" << endl;
    wordMap.Show(cout);
    
    return 0;
}

關鍵技術點解析

技術應用場景優勢
set<CWord>單詞去重、自動排序O(log n) 插入查找,天然有序
map<CWord,int>詞頻統計鍵值對映射,自動處理計數邏輯
istringstream單詞分割利用流運算子自動處理空白分隔
運算子重載自訂比較邏輯讓 STL 容器支援自訂類別

執行結果範例

單詞集合為
apple   banana  hello   world   
單詞及出現次數
apple   3
banana  1
hello   2
world   1

擴充建議

  1. 大小寫不敏感:轉換為統一大小寫後再統計
  2. 支援更多分隔符:擴充 delimset 包含標點、數字等
  3. Unicode 支援:改用 wstring 處理多語言文字
  4. 效能優化:大量資料可考慮 unordered_set/map(O(1) 平均複雜度)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved