读入、输出优化
关闭流同步
std::ios::sync_with_stdio(false);
关闭输入输出流与标准输入输出(scanf
printf
)的同步,加快流速度,但关闭后不可混用。
整形快读
从标准输入流读入一个 int
#include<cctype>
#include<cstdio>
inline int read(){
int x=0,w=0;char c=getchar();
while(!isdigit(c)) w|=c=='-',c=getchar();
while(isdigit(c)) x=x*10+c-'0',c=getchar();
return w?-x:x;
}
template
形式读入整形。
template <typename T>
inline T read(){
T x=0;int w=1;char c=getchar();
while(!isdigit(c)){if(c=='-')w=-1;c=getchar();}
while(isdigit(c))x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*w;
}
int main(){
long long a;
while(a=read<long long>())printf("%lld\n",a);
return 0;
}
fread 快读
fread 快的原因好像是一次将一大堆东西压入输入流中然后利用指针读入。
char buf[1<<21],*p1=buf,*p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline int read(){
int x=0,w=0;char c=getchar();
while(!isdigit(c)) w|=c=='-',c=getchar();
while(isdigit(c)) x=x*10+c-'0',c=getchar();
return w?-x:x;
}
注意,因为是一次性读入,在调试手动输入数据的时候记得加 Ctrl+Z 结束。
整形快输
输出一个整形
inline void write(int x) {
static int sta[35],top; top=0;
do {
sta[top++]=x%10,x/=10;
} while(x);
while(top) putchar(sta[--top]+'0');
}
fwrite 快输
char pbuf[1 << 20], *pp = pbuf;
inline void push(const char &c) {
if (pp - pbuf == 1 << 20) fwrite(pbuf, 1, 1 << 20, stdout), pp = pbuf;
*pp++ = c;
}
inline void write(int x) {
static int sta[35];
int top = 0;
do {
sta[top++] = x % 10, x /= 10;
} while (x);
while (top) push(sta[--top] + '0');
}
注意:与 fread 快读相同的原因,并不会实时输出。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现