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
");     //直接输出至控制台窗口
13 
14     *cin.tie() << "This is inserted into cout
";    // 空参数调用返回默认的output stream,也就是cout
15     prevstr = cin.tie(&ofs);    // cin绑定ofs,返回原来的output stream
16     *cin.tie() << "This is inserted into the file
";    // 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