读入及其优化:快读 & 快读不定个(多个)变量的方法 (可变模板参数快读)

众所周知 , c++常见的读入:

$\bullet $ 万能的 cin 大法,但却因流输入与 scanf 同步,在大数据中奇慢无比,只需关闭流同步,就能快的飞起。

划重点:前提是不能再使用 cstdio里的任何东西!包括但不限于scanf getchar

也就是加上一句。

ios::sync_with_stdio(false); 

$\bullet$ 很吊但是很累的 scanf ,这里不作叙述。

$\bullet$ 快速读入!

这是个好东西,因为读入字符比读入整型快,至于为什么。。。不知道,反正写就完了!

加上类模板定义可以更加方便,代码中用到的位运算在代码里解释。

template <typename T>//就是说T可以是int 、 long long 等任意类型
inline void read(T &x){
    x = 0;char ch = getchar();bool f = 0;
    while(ch < '0' || ch > '9'){if(ch == '-')f = 1;ch = getchar();}
    while(ch >= '0' && ch <= '9')x = (x<<1) + (x<<3) + (ch^48),ch=getchar();//因为二进制挪左移 i 相当于乘上 2^i 所以x * 2 + x * 8 = x * 10 
    if(f)x = -x;                                        //ch^48 等价 ch - '0' 
}

这样很好,但是一个个数输入是不是很累呢?

再加上这样的模板就可以随便读辣!

template <typename T,typename ...Args>
inline void read(T &tmp,Args &...tmps){read(tmp);read(tmps...);}

合起来就是这样的:

template <typename T>
inline void read(T &x){
    x = 0;char ch = getchar();bool f = 0;
    while(ch < '0' || ch > '9'){if(ch == '-')f = 1;ch = getchar();}
    while(ch >= '0' && ch <= '9')x = (x<<1) + (x<<3) + (ch^48),ch=getchar();
    if(f)x = -x;                                       
}
template <typename T,typename ...Args>
inline void read(T &tmp,Args &...tmps){read(tmp);read(tmps...);}

主程序的读入我们就可以:

read(a,b,c,d,e,f);//还可以无限加

希望能帮到您!

posted @ 2022-04-11 22:27  Xu_brezza  阅读(294)  评论(1编辑  收藏  举报