快读

为什么要用快读我就不说了反正就是很快就是了但是对于一些输入全是空格的毒瘤题目就算了吧好的我们开始记板子。

快读是可以写成template形式的但是我们一般只会用到int所以这里光放读int的。

1 #include<ctype.h>
2 #include<cstdio>//下面就不写头文件了
3 inline int read()
4 {
5     int x=0,w=1;char c=getchar();
6     while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
7 while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
8 return x*w;
9 }

当然还有直接更改值的差不多了其实

inline void read(&int x)
{
    int w=1;char c=getchar();x=0;
    while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
  while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
  x*=w; }

但是我还是大发慈悲地给你们写了template的形式。但是记住这样使用时一定要在前面加上<种类>所以太麻烦了。而且我们可以明显的发现这种形式是读不进浮点数和小数的。顶多读个long long什么的。

template <typename T>
inline T read()
{
    T x=0,w=1;char c=getchar();
    while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    return x*w;
}
int main()
{      //这段只是测试,模板在上面
    long long a;
    while(a=read<long long>())printf("%lld\n",a);//注意read<long long>()
    return 0;
}

当然也有取地址版的。

template <typename T>
inline void read(T &x)
{
    T w=1;char c=getchar();x=0;
    while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
    while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
    x*=w;
}
int main()
{      //同样是测试
    long long a;
    while(1)
    {
        read(a);//只是不需要声明type了
        printf("%lld\n",a);
    }
    return 0;
}

后记:

int w=1;
{if(c=='-')w=-1;c=getchar();}
return x*w;

可以再优化为

int w=0;
w|=c=='-',c=getchar();
return w?-x:x;

区别是速度和连续输入两次负号的结果。

快读一般只有大输入的题目才有点用。

我一定是太闲了才浪费时间记快读!!!

 UPD:发现我上面写的真的很鸡肋,真正的快肯定是要加fread的嘛!

fread快的原因好像是一次将一大堆东西压入输入流中然后利用指针读入。

char buf[1<<21],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline int read(){
    int x=0,w=0;char c=getchar();
    while(!isdigit(c))w|=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    return w?-x:x;
}

注意如果这样的话不能再用scanf了,但可以用sscanf在流中读入。

原文地址:https://www.cnblogs.com/BrotherHood/p/13060018.html