容器:set集合

set:

set类似于数学上集合,它不会有两个相同的元素,并且自动对set里的值从小到大排序。

自定义的类型也可以构造set,但必须定义“小于”运算符。

方法:

begin()  end()

删除函数:erase();    

插入元素:insert();

clear()--清除所有元素

count()--返回某个值元素的个数

empty()--判断是否为空集合

#每次输入一个元素,并输出集合,可以看出每次的值都从小到大排列
#include<iostream>
#include<sstream>
#include<string>
#include<set>
using namespace std;
int main() {
	set<int> s;
	int a;
	while(2) {
		cin>>a;
		s.insert(a);
		for(set<int>::iterator i=s.begin(); i!=s.end(); i++) {
			cout<<*i<<" ";
		}
	}
}
运行结果:
1
1 2
1 2 0
0 1 2 23
0 1 2 23 15
0 1 2 15 23 22
0 1 2 15 22 23 17
0 1 2 15 17 22 23

 

例题: 安迪的第一个词典(UVa  10815)

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

样例输入:
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
......       #节约篇幅未列完

code: 

#include<iostream>
#include<sstream>
#include<string>
#include<set>
using namespace std;
int main() {
set<string> Set;
string s,buf;
while(getline(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读取
	}
	stringstream ss(s);
	while(ss>>buf)
	Set.insert(buf);
}
for(set<string>::iterator i=Set.begin();i!=Set.end();++i)
{
	cout<<*i<<endl;
}
	
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值