集合:SET
set集合中元素不能重复
例题
输入一个文本,找出所有不同的单词(连续的字母序列),按字典序从小到大输出,单词不区分大小写。
样例输入:
Today is Sunday! On Sunday, I usually play basketball.
样例输出:
basketball
i
is
on
play
sunday
today
usually
解答
本题为了展示set的用法,直接使用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);
if(cin.get()=='\n')
break;
}
for(set<string>::iterator it=dict.begin(); it!=dict.end(); ++it)
cout<<*it<<endl;
return 0;
}