使用 scanf / printf

在默认情况下,std::cin/std::cout 是极为迟缓的读入/输出方式,而 scanf/printfstd::cin/std::cout 快得多。

然而有的时候使用scanf/printf进行输入输出十分繁琐,因此我们可以采取取消同步流的方式直接使用std::cin/cout

取消同步流传输

std::ios::sync_with_stdio(false)可以用来关闭stdio的兼容并解除std::cinstd::cout的绑定,从而达到较快的输入和输出。

但是在这样做之后要注意不能同时使用 std::cinscanf,也不能同时使用 std::coutprintf,但是可以同时使用 std::cinprintf,也可以同时使用 scanfstd::cout

std::cin.tie(0),cout.tie(0)可以用来解除std::cinstd::cout之间的绑定,从而进一步优化输入和输出。

但是要注意使用了这个以后不能再使用std::cout << endl原因在于endl不仅有换行的功能,同时也会刷新缓冲区,因此建议使用std::cout << '\n'进行换行,否则不会有优化提升。

使用getchar进一步读入优化

众所周知,getchar 是用来读入 1byte1 byte 的数据并将其转换为 char 类型的函数,且速度很快。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
inline void read(int &n)
{
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 << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
n = x * f;
}

以上代码可以做到比用scanf()函数快 55 倍的速度读入任意整数。读入 numnum 可写为 num = read();

使用putchar进一步输出优化

同样是众所周知,putchar 是用来输出单个字符的函数。

1
2
3
4
5
6
7
8
inline void write(int x) {
if (x < 0) { // 判负 + 输出负号 + 变原数为正数
x = -x;
putchar('-');
}
if (x > 9) write(x / 10); // 递归,将除最后一位外的其他部分放到递归中输出
putchar(x % 10 + '0'); // 已经输出(递归)完 x 末位前的所有数字,输出末位
}
1
2
3
4
5
6
7
8
inline void write(int x) {
static int sta[35];
int top = 0;
do {
sta[top++] = x % 10, x /= 10;
} while (x);
while (top) putchar(sta[--top] + 48); // 48 是 '0'
}

更极致的输入和输出

个人感觉没有什么必要,不做解释,阐述如下。

读入、输出优化 - OI Wiki

Reference

读入、输出优化 - OI Wiki