set就是数学上的集合,每个元素最多只出现一次。和sort一样,自定义类型也可以构造set,但同样必须定义“小于”运算符。
以下是该题的代码:由于string已经定义了“小于”运算符,因此直接使用set保存单词集合即可。注意,输入时把所有非字母的字符变成空格,然后利用stringstream得到各个单词即可。
#include <iostream>
#include <string> //需要定义字符串变量
#include <set> //引入集合容器
#include <sstream>
using namespace std;
set<string> dict; //声明一个string集合
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]); //tolower函数,将字母转化为小写字母
else //如果是别的符号
s[i] = ' ';//用空格代替,使得下一步用stringstream来分割开各个单词
stringstream ss(s);
while (ss>>buf) //转化
dict.insert(buf);//insert函数,向dict集合中添加一个buf
}
for (set<string>::iterator it = dict.begin();it !=dict.end(); ++it) //iterator为迭代器
{
cout << *it << endl; //输出
}
return 0;
}
由于集合容器本身的性质,容器中默认从小到大,省了按字典序排序的过程。
关于stringstream的总结:
https://blog.csdn.net/u012878503/article/details/80405823