关闭stdio兼容
C++为了更好的兼容C,设置了一个公共缓冲区用于同步两种IO流, 这使得使用者能混合使用C/C++的标准IO, 但也带来了一定性能损失.
ios_base::sync_with_stdio(false);
这句代码可以解除兼容, 但代价就是当混合使用C/C++的IO时可能不会得到你预期的结果
如
printf("hello ");
cout << "world ";
你不能确保它会输出```hello world "还是"world hello "
至于cin 和scanf就更不用说了, 后果会更严重.
If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C+±style I/O an adventure.
Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).
解除IO流的绑定(tie)
cin.tie(NULL); cout.tie(NULL);
这将cin从cout上解开。绑定流确保在对另一个流执行每个I/O操作之前自动刷新一个流。
默认情况下,cin与cout绑定,以确保合理的用户交互。例如:
std::cout<<“输入名称:”; std::cin>>名称;
如果cin和cout是绑定的,可以确保在程序提示用户输入之前执行输出。如果解开绑定,程序可能会阻止等待用户输入其名称,但“输入名称”消息尚不可见(因为cout在默认情况下是缓冲的,只有在需要时或缓冲区已满时,才会在控制台上刷新/显示输出)。
So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.
In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.
当然, 以上一切副作用, 对于刷算法题来说是等于没有的, 只是不能c/c++IO流混用



