讀入多行文本,每行統計不同單詞數量。單詞由空格分隔,遇到 # 獨佔一行結束。
set<string> 自動去重stringstream 自動處理多空格、製表符等分隔符getline,清空 set,分詞插入,輸出大小#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string line;
while (getline(cin, line)) {
if (line == "#") break;
set<string> dict;
stringstream ss(line);
string word;
while (ss >> word) dict.insert(word);
cout << dict.size() << '\n';
}
return 0;
}
不使用 stringstream 時,需手動遍歷字符串,跳過空格,提取連續非空格字符。標準庫版本更簡潔、健壯,推薦實戰使用。
getline 保留空格,適合整行處理stringstream 構造函數接受 string,operator>> 自動按空白字符分割set 基於紅黑樹,插入查詢 O(log n),自動有序去重dict.clear()此題是 C++ STL 容器與流操作的基礎練習,掌握 set+stringstream 組合可輕鬆解決多數單詞統計問題。