1. 程式人生 > 其它 >讀入及其優化:快讀 & 快讀不定個(多個)變數的方法 (可變模板引數快讀)

讀入及其優化:快讀 & 快讀不定個(多個)變數的方法 (可變模板引數快讀)

眾所周知 , 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);//還可以無限加

希望能幫到您!