读入优化

scanf比cin快

但有比scanf更快的

当你cin这样的时候

就要改用scanf

要更快

快读

#include<iostream>
using namespace std;
void read(int &x){
    char s=getchar();int f=1;x=0;
    while('0'>s||s>'9'){if(s=='-')f=-1;s=getchar();}
    while('0'<=s&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
int main()
{
    int a;
    read(a);
    cout<<a;
}

6.17

玄学优化

比getchar还快的fread

读入只能是文件

#include<iostream>
#include<cstdio>
char buf[1000001],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++)
inline int read() {
    char c=getchar();int x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
int main()
{
    freopen("a.txt","r",stdin);
    int a;
    a=read();
    std::cout<<a;
    return 0;
}
View Code

注意事项

切记:不要与scanf()混用!因为(文件流的一些内容可能已经被加载到缓存空间里了 )
不过在第一次使用fread()之前还是可以scanf()的

7.3

又看到一个不知道算不算优化的地方

n=n*10+s-'0'

n=(n<<3)+(n<<1)+s-48;

原文地址:https://www.cnblogs.com/dsrdsr/p/8991521.html