cin的优化

  虽然C++有cin函数,但看别人的程序,大多数人都用C的scanf来读入,其实是为了加快读写速度,难道C++还不如C吗!?其实cin效率之所以低,不是比C低级,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而且是C++为了兼容C而采取的保守措施。

  先讲一个cin中的函数——tie,证明cin和scanf绑定是同一个的流。

  tie是将两个stream绑定的函数,空参数的话返回当前的输出流指针。

  先码代码:

 1 #include <iostream>
 2 #include <fstream>
 3 #include <windows.h>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     ostream *prevstr;
10     ofstream ofs;
11     ofs.open("test.out"); 
12     printf("This is an example of tie method\n");     //直接输出至控制台窗口
13 
14     *cin.tie() << "This is inserted into cout\n";    // 空参数调用返回默认的output stream,也就是cout
15     prevstr = cin.tie(&ofs);    // cin绑定ofs,返回原来的output stream
16     *cin.tie() << "This is inserted into the file\n";    // ofs,输出到文件
17     cin.tie(prevstr);    // 恢复原来的output stream
18     ofs.close();    //关闭文件流
19     system("pause");
20     return 0;
21 }

     控制台内的输出:

1 This is an example of tie method
2 This is inserted into cout
3 请按任意键继续...

  文件内输出:

1 This is inserted into the file

sync_with_stdio

  回到重点,现在知道 tie 可以绑定 Stream ,其实也可以解绑,只需要绑定空值( 0 或 null 皆可),所以可以用此方法解绑 cin 和 scanf 。

#include <iostream>
int main() 
{
    std::cin.tie(0);
    return 0;
}

   还有一种方法,调用函数 sync_with_stdio(false),这个函数是一个“是否兼容 stdio 的开关,C++ 为了兼容 C ,保证程序在使用了 std::printf 和std::cout 的时候不发生混乱,将输出流绑到了一起。可以与 tie 函数一同使用:

#include <iostream>
int main() 
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    return 0;
}

   这样,cin 的速度就可以与 scanf 的速度相比了。

转载于:https://www.cnblogs.com/Bita/p/5929087.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值