安迪的第一個字典(Andy's First Dictionary,Uva 10815)
輸入一個文本,找出所有不同的單詞(連續的字母序列),按字典序從小到大輸出。單 詞不區分大小寫。
樣例輸入:
Adventures in Disneyland
Two blondes were going to Disneyland when they came to a fork in the road.
The sign read: "Disneyland Left." So they went home.
樣例輸出(為了節約篇幅只保留前5行):
a
adventures
blondes
came
disneyland
【分析】
本題沒有太多的技巧,只是為了展示set的用法:由于string已經定義了“小于”運算符, 直接使用set保存單詞集合即可。注意,輸入時把所有非字母的字符變成空格,然后利用 stringstream得到各個單詞。
#include <iostream> #include<string> #include<set> #include<sstream> using namespace std; set<string> dict; //string 集合 int main(){ string s,buf; while(cin>>s){ for(int i=0;i<s.length();i++){ if(isalpha(s[i])) s[i]=tolower(s[i]);else s[i]=' '; } stringstream ss(s); while(ss>>buf ) dict.insert(buf); } for(set<string>::iterator it = dict.begin();it!=dict.end();++it){ cout<<*it<<"\n"; } return 0; }
上面的代碼用到了set中元素已從小到大排好序這一性質,用一個for循環即可從小到大 遍歷所有元素。iterator的意思 是迭代器,是STL中的重要概念,類似于指針。和“vector類似于數組”一樣,這里的“類似”指 的是用法類似。

浙公網安備 33010602011771號