栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++输入输出优化及其副作用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++输入输出优化及其副作用

关闭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流混用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997481.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号