安迪的第一个字典(set容器)

2 篇文章 0 订阅
问题:

        输入一个文本,找出所有不同的单词(连续的字母序列),按字典从小到大输出,单词不分大小写。

样例输入:
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.


样例输出:
a
adventures
blondes
came
disneyland
fork
going
home
in
left
read
road
sign
so
the
they
to
two
went
were

when

#include<iostream>
#include<set>
#include<string>
#include<sstream>
using namespace std;
set<string> dict;
int main()
{
	string s, buffer;
	while (cin>>s)
	{   
		//设置一个出口
		if (s[0] == '#')
			break;
		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>>buffer)
		{
			dict.insert(buffer);
		}
	}
	for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
	{
		cout << *it << "\n";
	}
	return 0;
}

注意:

       stringstream 的头文件是#include<sstream>

       它是字符串流,经常被用来作为数据切分或类型转化。

       eg: 将string转为int型

#include<iostream>
#include<sstream>

using namespace std;
int main()
{
	string result ="10000";
	stringstream stream;
	int n = 0;
	stream << result;
	stream >> n;//n等于10000
	cout << n + 1;//n输出10001
	return 0;
}

set知识点总结:

     set简介:关于set,必须说明的是set关联式容器。set作为一个容器也是用来存储同一数据类型的数据容器,并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序

     set常用方法:       

begin()        ,返回set容器的第一个元素

end()      ,返回set容器的最后一个元素

clear()          ,删除set容器中的所有的元素

empty()    ,判断set容器是否为空

max_size()   ,返回set容器可能包含的元素最大个数

size()      ,返回当前set容器中的元素个数

rbegin     ,返回的值和end()相同

rend()     ,返回的值和rbegin()相同

#include<iostream>
#include<set>

using namespace std;
int main()
{
	set<int> a;
	a.insert(1);
	a.insert(2);
	a.insert(7);
	a.insert(8);
	cout << "set容器的大小" << a.size() << endl;
	cout << "set容器的最大值" << a.max_size() << endl;
	cout << "set中的第一个元素" << *a.begin() << endl;
	//end指向的是末端元素的下一个位置,是未定义的
	//cout << "set中的最后一个元素" << *a.end() << endl;
	cout << "set中的最后一个元素" << *a.rbegin() << endl;
	return 0;
}

           count() 用来查找set中某个某个键值出现的次数。这个函数在set并不是很实用,因为一个键值在set只可能出现0或1次,这样就变成了判断某一键值是否在set出现过了。(在下一个习题中,我会用到这个函数)

  疑问:

          rbegin()     ,返回的值和end()相同

           为啥上面那个列子用a.end()和rbegin()会出现不同的结果。        

  翻阅了一下手册,发现了它们确实不一样:

 end():末尾之后的元素是容器中最后一个元素之后的元素,是一个“理论上的元素”,实际并不存在,因此指向它的迭代器不能够被解引用(Dereferenced)。

 rbegin():set::rbegin 返回值指向的元素刚好是 set::end 返回值指向的元素的前一个元素。

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值