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 的速度相比了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM