UVa 10815 Andy’s dictionary
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;
set<string>dict;//set is template need to give it a type
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] = ' ';//if not alpha make it whitespace
stringstream ss(s); //constructor
while (ss >> buf) dict.insert(buf);
}
for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
cout << *it << "\n";
return 0;
}
Note:
-
set
set 属于STL,是一个集合(each element has unique value and cannot be modified)
使用set时,重复输入的数据只会存一次 -
stringstream
可以理解为一个class,use to treat string as stream 我感觉stringstream ss(s);
类似一个拷贝构造函数。将括号内的s复制粘贴到ss中,为啥非再弄个新的类来存储s?
先说cin读取string,会读取空格,只会在回车符之后完结一次读取,这就是输入流吗。while (cin >> s)
,利用if the input is successful, cin will yield true and vice versa.读取未知的输入。
**NOTE:cin返回false时也可以是你输入的和接受类型不匹配。**比如说我一个int变量,你输入了char,会自动退出读取过程。但是string的话,字符数字都能读进去。
while (cin >> s)
{
for (int i = 0; i < s.length(); i++)
if (isalpha(s[i]))
s[i] = tolower(s[i]);
else s[i] = ' ';//if not alpha make it whitespace
dict.insert(s);
}
for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
cout << *it << "\n";
return 0;
但是,当我没有用stringstream ss(s)
甚至不用buf
,仍然运行成功而且效果和之前是一样的。
so,为啥要这个东西?
- 最后再说iterator,STL里面类似指针的东西,注意使用前声明作用域,如果细说,iterator可以分为五个类,有用于output,input,还有random等等,但是。。感觉没必要背概念,懒得总结(摘抄)了
SIDENOTE:这个程序结束输入需要ctrl+z+enter
,然而我还是狂敲键盘好久才停下来它,很迷