【模板】快速读入/读入优化

蒟蒻输入成长史

放个板子在这

测试了几个输入方法,发现几种输入方法的速度大致为: c i n &lt; &lt; s c a n f &lt; c i n ( 关 闭 流 同 步 ) &lt; r e a d &lt; &lt; f r e a d cin&lt;&lt;scanf&lt;cin(关闭流同步)&lt;read&lt;&lt;fread cin<<scanf<cin()<read<<fread

  • 入门教的是用 c i n cin cin
cin>>x
  • noip普及组时才知道用 s c a n f scanf scanf(有些联赛题说要用高效的读入方式,用这个就好)
scanf("%d$d",&x,&y);
  • 有人会接触到 c i n cin cin的关闭流同步,不过这玩意儿好像在NOI中不能用?而且关闭流同步后就不能读入 s t r i n g string string类型了
ios::sync_with_stdio(false);  
cin>>x;
  • 再后来省选,听dalao们说有种东西叫做读入优化 r e a d read read,原理是将数字按照数位一个个读进来(比如数字 327 327 327 就会依次读入 3 , 2 , 7 3,2,7 3,2,7,每次将数字乘 10 10 10 再加当前数字)(代码的 template <... 是为了能同时读入多种类型变量 ( u n s i g n e d ) i n t , l o n g l o n g , s h o r t (unsigned)int,longlong,short (unsigned)int,longlong,short 都行)
template <typename _tp> inline _tp read(_tp&x){
	char ch=getchar(),sgn=0;x=0;
	while(ch^'-'&&!isdigit(ch))ch=getchar();if(ch=='-')ch=getchar(),sgn=1;
	while(isdigit(ch))x=x*10+ch-'0',ch=getchar();if(sgn)x=-x;return x;
}

int main(){b=read(a);}
  • 准备全国赛时发现一道正解被卡成 25 p t s 25pts 25pts,数据量达 2 × 1 0 6 2\times 10^6 2×106 f r e a d fread fread 表现优秀(这里和上头差不多,只不过是一次性读入一大串字符, g c ( ) gc() gc() 函数每调用一次返回一个字符,相当于楼上的 g e t c h a r ( ) getchar() getchar()
struct ios {
    inline char gc(){
        static const int IN_LEN=1<<18|1;
        static char buf[IN_LEN],*s,*t;
        return (s==t)&&(t=(s=buf)+fread(buf,1,IN_LEN,stdin)),s==t?-1:*s++;
    }

    template <typename _Tp> inline ios & operator >> (_Tp&x){
        static char ch,sgn; ch = gc(), sgn = 0;
        for(;!isdigit(ch);ch=gc()){if(ch==-1)return *this;sgn|=ch=='-';}
        for(x=0;isdigit(ch);ch=gc())x=x*10+(ch^'0');
        sgn&&(x=-x); return *this;
    }
} io;

int main(){io>>a>>b;}
  • 16
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值