之前说了一下STL中的排序和检索,今天做了一个可以用到set的题目。所以就写一篇博客记录一下。
集合是一个常用的容器。set就是数学上的集合—每个元素最多只出现一次,和sort一样自定义类型也可以构造set,但必须定义小于运算符;
题目大意来源:UVa 10815(安迪的第一个字典)
题面:输入一个文本,找出所有不同的单词(或连续的字母序列),按字典序从小到大输出。单词不区分大小写。
样例输入:
Adventure in Disneyland
Two blonds were going to Disneyland when they came to a fork in the road.The sign read:Disneyland Left.
So they went home.
样例输出(太难输了 就放五个吧 我放一张输出的图在下面):
a
adventure
blondes
came
disneyland
分析:
我们首先需要将里面所有的单词或者连续的字母序列进行标准化,标准化的含义也就是将所有的元素全部转换为小写字母,然后再把所有的单词装入到集合中,然后使用一个for循环就可以从小到大遍历这个集合并且输出。
代码如下:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <cctype>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <sstream>
using namespace std;
set<string> dict;
int main()
{
string s;
string buf;
while (cin >> s) //这种方式的循环输入 结束输入的办法是在输入完文本之后 按住ctrl z然后回车即可
{
for (int i = 0; i < s.length(); ++i)
{
if (isalpha(s[i]))
{
s[i] = tolower(s[i]);
}
else
{
s[i] = ' ';
}
}
stringstream ss(s); //包含在头文件<sstream>
//将每一个单词输入到集合中
while (ss >> buf)
{
dict.insert(buf); //输入到集合中
}
}
for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
{
cout << *it << endl;
}
return 0;
}
输出如下图所示:
end