使用 C++ STL 容器 set 與 map 實作單詞去重統計與詞頻計數,展示標準庫演算法在文字處理中的實際應用。
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;
}
};
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";
}
};
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
delimset 包含標點、數字等wstring 處理多語言文字unordered_set/map(O(1) 平均複雜度)