输入输出流优化

众所周知,由于某些难以描述的原因,cin输入效率远远低于了scanf。所以,我们为了加速读入读出,找到了一些诡异的读入板子。

此篇仅用作模板速用,不讨论其原理以及争议。

关闭同步流 

针对cin的优化。速度大概能达到scanf级。

    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

Read函数(短)

这个弊端是对于整数貌似读不了long long(我记得不行)

而且效率虽然快与sacnf,但并不是最快的那个。

void Read(int &x)
{
    int f=1;x=0;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}

我注意到在开iostream头文件的时候,dev是给出了read的函数提示的。也就是说,不确定read是否会产生冲突。

为了保险起见,我们将自己写的读入函数首字母大写。即Read()

Read双函数(长)

这个是目前我见识到的最快的读入方法。而且他支持long long 类型。

但是弊端显而易见,很长,而且两个函数还附带一个不算很低的数组。

在用的时候要小心卡内存的情况。可以适当调低数组大小

const int MAXSIZE=1<<12;
inline char gc()
{
    static char In[MAXSIZE], *at = In, *en = In;
    if (at == en)
    {
        en = (at = In) + fread(In, 1, MAXSIZE, stdin);
    }
    return at == en ? EOF : *at++;
}
inline long long Read()
{
    char c;
    while (c = gc(), !(c >= '0'&&c <= '9') && c != '-') {}
    bool f = c == '-';
    long long x = f ? 0 : c - '0';
    for (c = gc(); c >= '0'&&c <= '9'; c = gc())
    {
        x = x * 10 + c - '0';
    }
    return f ? -x : x;
}

猜你喜欢

转载自www.cnblogs.com/Uninstalllingyi/p/11579469.html