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;
}
}