C++输入输出 & 优化

本章介绍C++的输入输出及其优化(参考oi wiki
对于普通的输入输出,可以这样写

#include <iostream>
using namespace std;
int a, b;
int main() {
    cin >> a >> b;
    cout << a << ' ' << b << endl; 
    return 0;
}

但使用cin和cout效率太低,怎么办?
有两种解决方法

第一种

#include <iostream>
using namespace std;
int a, b;
int main() {
    ios::sync_with_stdio(0);cin.tie(0); // 等价于cin.tie(0)->sync_with_stdio(0);
    cin >> a >> b;
    cout << a << ' ' << b << endl; 
    return 0;
}

上述代码使用 ios::sync_with_stdio(0); 来关闭与C流的同步,C++ 为了兼容C,也就是为了保证程序在同时使用了 printf 和 cout 时不发生混乱,因此对这两种流进行了同步。同步的C++流保证是线程安全的。

第二种

#include <iostream>
using namespace std;
int a, b;
int main() {
    scanf("%d %d", &a, &b);
    printf("%d %d", a, b);
    return 0;
}

上述代码该 cin 和 cout 为 scanf 和 printf,scanf 和 printf 的输入时间比 cin 和cout 快

注意

如果你使用关闭同步的方法,那就不能同时使用 cin 和 scanf,也不能同时使用 cout 和 printf,但可以同时使用 cin 和 printf,以及 cout 和 scanf

如果你还觉得慢,那就让我们俗称的快读快输来帮助你吧

代码
#include <iostream>
using namespace std;
inline int read() { // inline加不加无所谓 
	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 << 3) + (x << 1) + ch - '0';
		ch = getchar();
	}
	return x * f;
}
void write(int x) {
	if (x < 0) {
		putchar('-');
		x = -x;
	}
	if (x > 9) {
		write(x / 10);
	}
	putchar(x % 10 + '0');
	return;
}
int a, b;
int main() {
	a = read(), b = read();
	write(a);
	cout << ' ';
	write(b);
	return 0;
}
posted @ 2025-07-01 14:10  终是遗憾退场  阅读(27)  评论(0)    收藏  举报