既然你们都会快读int,那我来一发快读string。
由于cin读string太慢,而scanf()又读不了string,所以我准备写一个string的快读。
其实string的快读比int还简单,因为不需要“过滤杂项”“判断是否为负数”这么多复杂的东西。
上代码:
#include<stdio.h>
#include<string>
using namespace std;
string readstr(int mode){//我不确定能不能加inline
string ans="";//别忘了初始化
char tmp;
while(1){//由于跳出循环的条件既不适合设在开头也不适合设在末尾,我就设了死循环,然后在中间加判断
tmp=getchar();//读入
if(!(tmp>=33&&tmp<=126)&&mode==1||(tmp=='\n'||tmp=='\r'||tmp==EOF)&&mode==2||tmp==EOF&&mode==3)//设置边界条件(模式一所有可见字符都在这个范围内)(一开始模式一写反了,忘了!,感谢@caijianhong 提醒)(注意运算符优先级:!最高,&&其次,||最低)
break;//退出循环
else
ans+=tmp;//添加在末尾
}
return ans;
}
int main(void){
string a=readstr(1);//就这么简单
return 0;
}再放一版没注释的:
string readstr(int mode){
string ans="";
char tmp;
while(1){
tmp=getchar();
if(!(tmp>=33&&tmp<=126)&&mode==1||(tmp=='\n'||tmp=='\r'||tmp==EOF)&&mode==2||tmp==EOF&&mode==3)
break;
else
ans+=tmp;
}
return ans;
}实测效率(模式一):
字符串个数:
每个字符串长度:
快读耗时:
cin耗时:
快了差不多一倍!
更新日志:
- 惊讶的发现关了同步流的
cin只需要?¿(和上面的“实测效率”条件一样) - 添加模式选项:
- 模式一:过滤所有空白字符
- 模式二:过滤换行符(每次读入一行)
- 模式三:不过滤任何字符
- 增加一版没注释的,方便使用。
- 将没注释的改为仅
readstr函数,去掉头和int main。