读入及其优化:快读 & 快读不定个(多个)变量的方法 (可变模板参数快读)
众所周知 , c++常见的读入:
∙ 万能的 cin 大法,但却因流输入与 scanf 同步,在大数据中奇慢无比,只需关闭流同步,就能快的飞起。
划重点:前提是不能再使用 cstdio里的任何东西!包括但不限于scanf getchar
也就是加上一句。
ios::sync_with_stdio(false);
∙ 很吊但是很累的 scanf ,这里不作叙述。
∙ 快速读入!
这是个好东西,因为读入字符比读入整型快,至于为什么。。。不知道,反正写就完了!
加上类模板定义可以更加方便,代码中用到的位运算在代码里解释。
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);//还可以无限加
希望能帮到您!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下