C++STL库之set

之前说了一下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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值