大家都知道 c++ 兼容完整的 c,从理论上来讲 cin 和 cout 的速度应该远远大于 c 中 scanf 和 printf。
但是在真真做题的时候,当数据输入次数足够多的时候,用 cin/cout 的会超,而用 scanf/printf 则能过题,这是为什么?
在 codeforces 中会出现 TLE 的情况,并且官方题解通常也会带着这些宏:
#define PSB push_back
#define ll long long
#define FastIO ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);
constexpr ll mod = 1e9 + 7;
const ll N=3e6+5;
那么这里的 FastIO 是什么?有什么用?
# scanf("%d")
当然,全部转换为 scanf 和 printf 就会变快
For example scanf and printf are undoubtedly faster than cin and cout, but the later two are easier and faster to code. How should we adress this tradeoff?
因为 Cpp 默认开启兼容 c 语言的模式,所以为了保证程序在使用了 std::printf 和 std::cout 的时候不发生混乱,将输出流绑到了一起。
Just include std::ios::sync_with_stdio(false);
in your code, and cin will be as fast as scanf. (inside method main)
# sync_with_stdio
默认情况,cin 与 stdin 总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时 cout 和 stdout 也一样,两者混用不会输 出顺序错乱。正因为这个兼容性的特性,导致 cin 有许多额外的开销,如何禁用这个特性呢?只需一个语句 std::ios::sync_with_stdio(false);
,这样就可以取消 cin 于 stdin 的同步了,此时的 cin 就与 scanf 差不多 了。
另一种解释: cout 在输出时总是要先将输出的存入缓存区。而 printf 直接调用系统进行 IO,它是非缓存的。所以 cout 比 printf 慢。
# tie
tie 是 tuple 库中的一个函数, std::tuple
C++ tuple 的介绍及使用 (opens new window)
std::tuple 和 std::tie 的用法简介 (opens new window)
std::cin.tie (0) 或 std::cin.tie (NULL) 该函数取消 cin 和 cout 的绑定。
tie 是将两个 stream 绑定的函数,空参数的话返回当前的输出流指针。
所以为了加速输入输出:
定义宏:
#define FastIO ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);
main 函数中调用:
FastIO
即可