在开始做这个题目之前,我们首先需要知道set的基本用法:
这些是它的常用函数:
insert();//插入一个元素;
count();//判断容器中是否存在某个元素
earse();//删除集合中某个元素
clear();//清空集合
此外,与vector不同的是,set并不能用下标法来来遍历,我们使用迭代器;
set<int> s;
for(set<int>::iterator it=s.begin();it!=s.end();it++) cout<<*it<<'\n;
问题:输入一个文本,找出所有不同的单词(连续的字母序列),按字典序从小到大输出。单词不区分大小写。
输入:
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
......
利用set可以自动排好序(默认升序)的特性,用一个string类型的set容器来存放输入的单词,再利用迭代器将元素输出即可。由于文本存在非字母字符,我们可以使用isalpha()和tolower函数处理字符串(题目要求不区分大小写)。代码如下:
#include <bits/stdc++.h> using namespace std; set<string> dict; int main() { string s, buf; while (cin >> s) { 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 >> buf) dict.insert(buf); } for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it) cout << *it << '\n'; return 0; }
这其中还有一个需要提及的是stringtream的使用。我是这样理解的,把每次输入的字符串s经过处理(大写换小写、非字母被去除)存入一片缓冲区,从缓冲区中每读出一个字符串,将它添加到set中。