set应用:提取文本中所有不同的单词
set应用:提取文本中所有不同的单词
set是一个常用的容器,是数学意义上的集合–每个元素最多只能出现一次。和sort函数一样,自定义的类型(struct、class)也可以构造set,但是同样必须定义“小于”运算符。
例题:
输入一个文本,找出所有不同的单词,按照字典序从小到大输出。单词不区分大小写,大写的单词按小写输出。这里的单词定义为连续的字母序列。
样例输入:
I am a student from HUST.
样例输出
a
am
from
hust
i
student
程序代码:
#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<<endl;
return 0;
}
程序运行结果:
输入文本:
Adventures in Disneyland
Two blondes were going to Disneyland.
They were driving on the Interstate when they saw a sign that said Disneyland LEFT.
They started crying and turned around and went home.
运行结果: