读入优化之fread
参考资料:https://blog.csdn.net/FYOIER/article/details/72667544
我以前写的读入优化是这个样子的:
template <class T>
void rd(T &x) {
x = 0; char ch = getchar(); bool f = false;
while ((ch < '0' || ch > '9') && (ch != '-')) ch = getchar();
if (ch == '-') f = true, ch = getchar();
while (ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + ch - '0',
ch = getchar();
if (f) x = -x;
}
其实我一直知道有一种更加快速的读入优化,可是因为这个读入优化已经够用了,再加上 fread 的读入优化长成这样:(用这个 nc() 函数代替 getchar() 即可)
inline char nc(){
static char buf[1000000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
实在是太难背了,所以就一直没有学,知道今天我碰到一道需要读入 毒瘤题,所以就不得不用这个了。其实这个能够理解的,重点在于这句话:
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
运用了大量的三目运算符([bool]?val1:val2),我们来分析一下:
p1表示头指针,p2表示尾指针(左闭右开)p1==p2表示buf中的字符已经读完了,所以p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin)读入一个新的buf、重置头尾指针- 如果这个时候
p1==p2仍然成立,说明已经读完,返回EOF