Hanwan Space

读入优化板子


总是忘记读入优化的板子,在这里 Mark 一下。

需要 cstdiocctype 头文件

不能读负数版(异或 48 是一个神奇的操作)

cpp
template<typename Tp> inline void read(Tp &x) {
	char c = getchar();
	x = 0;
	while (!isdigit(c)) c = getchar();
	do {
		x = x * 10 + (c ^ 48);
		c = getchar();
	} while (isdigit(c));
}

可以读负数版(因为需要额外的计算,比上面的稍慢一点,但依然吊打自带的读入)

cpp
template<typename Tp> inline void read(Tp &x) {
	char c = getchar(); int f = 1; x = 0;
	if (c == '-') f = -1;
	while (!isdigit(c))	c = getchar();
	do {
		x = x * 10 + (c ^ 48);
		c = getchar();
	} while (isdigit(c));
	x *= f;
}

上面的读入优化有一个缺点,就是当一次要读入很多数而且不能用循环的时候,需要一个一个手打 read(),比如 read(a), read(b), read(c); 这样远不如 cincin >> a >> b >> c;scanf()scanf("%d%d%d", &a, &b, &c); 来得方便。 不过 cstdarg 库拯救了我们!只需要加上这个头文件:

cpp
template <typename Tp, typename... Args>
inline void read(Tp& t, Args&... args) {
	read(t); read(args...);
}

这样就可以愉快使用 read(a, b, c) 这样的形式来读入了,而且似乎比标准读入方式更方便了。


如果上面两个都不想打,可以考虑这个

cpp
std::ios::sync_with_stdio(false);

cincout 输入输出即可(格式化输入输出就不能用了)。 实机测试居然比格式化输入快


  • 板子
  • 读入优化
© hawa130转载请注明出处
License: CC BY-NC-SA 4.0

上一篇

Tarjan 的实际应用 — 题解集合

下一篇

骗分神器 bitset 介绍 & 使用