在算法竞赛中,当题目输入规模达到百万级别时,标准库的cin和cout如果没有关闭同步就会显得很慢,而手写基于getchar和putchar的缓冲IO能明显提升读写效率。下面介绍一种通用的C++快速IO读写模板实现方式。

为什么需要快速IO
大型输入输出场景下,系统调用次数直接影响耗时。标准输入输出函数存在较多格式解析与缓冲开销。自己控制字符读取和写入,可以避免不必要的处理。
快速读入模板
以下代码使用getchar实现整数与字符的快速读入,支持负数,并利用inline减少调用开销。
#include <cstdio>
// 快速读入整数
inline int readInt() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return x * f;
}
// 快速读入字符,跳过空白
inline char readChar() {
char ch = getchar();
while (ch == ' ' || ch == 'n' || ch == 'r' || ch == 't') {
ch = getchar();
}
return ch;
}
快速输出模板
使用putchar将整数逐位写出,比printf更高效。注意递归输出高位数字。
#include <cstdio>
// 快速输出整数
inline void writeInt(int x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) writeInt(x / 10);
putchar(x % 10 + '0');
}
// 快速输出字符
inline void writeChar(char ch) {
putchar(ch);
}
使用建议
- 若使用cin和cout,请在执行前调用
ios::sync_with_stdio(false)并取消cin.tie(nullptr)。 - 避免在使用快速IO时混用scanf或cin,可能造成缓冲混乱。
- 用
'n'代替endl,减少刷新缓冲区的次数。
整合示例
下面给出一个整合读写的简单主函数示例,读取两个整数并输出它们的和。
#include <cstdio>
inline int readInt() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return x * f;
}
inline void writeInt(int x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) writeInt(x / 10);
putchar(x % 10 + '0');
}
int main() {
int a = readInt();
int b = readInt();
writeInt(a + b);
putchar('n');
return 0;
}
将上述模板加入自己的竞赛代码库,即可在OI或ACM赛事中应对绝大多数大数据IO场景。