set:集合
#include <set>
set就是数学上的集合,每个元素最多只出现一次,并且默认将其中的元素从小到大排序,用一个for循环就可以直接输出从小到大的元素。
set的一些操作:
begin()--返回指向第一个元素的迭代器
clear()--清除所有元素
count()--返回某个值元素的个数
empty()--如果集合为空,返回true
end()--返回指向最后一个元素的迭代器
insert()--在集合中插入元素
size()--集合中元素的数目
swap()--交换两个集合变量
find()--返回指向该元素的迭代器。
UVA10815 Andy’s First Dictionary
Andy, 8, has a dream - he wants to produce his very own dictionary. This is not an easy task for him, as the number of words that he knows is, well, not quite enough. Instead of thinking up all the words himself, he has a briliant idea. From his bookshelf he would pick one of his favourite story books, from which he would copy out all the distinct words. By arranging the words in alphabetical order, he is done! Of course, it is a really time-consuming job, and this is where a computer program is helpful.
You are asked to write a program that lists all the different words in the input text. In this problem, a word is defined as a consecutive sequence of alphabets, in upper and/or lower case. Words with only one letter are also to be considered. Furthermore, your program must be CaSe InSeNsItIvE. For example, words like “Apple”, “apple” or “APPLE” must be considered the same.
Input
The input file is a text with no more than 5000 lines. An input line has at most 200 characters. Input is terminated by EOF.
Output
Your output should give a list of different words that appears in the input text, one in a line. The words should all be in lower case, sorted in alphabetical order. You can be sure that he number of distinct words in the text does not exceed 5000.
Sample Input
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.
Sample Output
a
adventures
blondes
came
disneyland
fork
going
home
in
left
read
road
sign
so
the
they
to
two
went
were
代码:
#include <iostream>
#include <string>
#include <set>
#include <cctype>
#include <sstream>//字符串流头文件
using namespace std;
set<string> dict;//string集合
int main()
{
string s, buf;
while (cin>>s){//注意cin读到空白字符结束
for (int i=0; i<s.length(); i++)
if (isalpha(s[i]))//如果是字母,变成小写
s[i]=tolower(s[i]);
else
s[i]=' ';
stringstream ss(s);//得到各个单词 保存在stringstream对象的内部缓冲中 自动分配存储空间。
while (ss>>buf)//每次将一个单词给buf
dict.insert(buf); //在集合中插入元素
}
for (set <string>::iterator it=dict.begin(); it!=dict.end(); it++)//string里没有定义<运算符,所以用!=
cout<<*it<<endl;
return 0;
}