iostream/fstream中的輸入輸出資料流指標的綁定,tie函數的使用。

來源:互聯網
上載者:User

標籤:功能   /var   原因   定義   tput   介紹   tle   style   over   

 

為了相容c語言的輸入輸出,c++裡面採用tie將輸入輸出資料流經行綁定,所以cin/cout並不是獨立的。當執行cin時,cout同時會被執行。反之亦然。

by defalut,cin is tied to cout,and wcin is tied to wcout。

預設情況下,cin和cout是綁定在一起的,wcin和wcout是綁定在一起的。

也就是說預設情況下,我們執行

int a;cin>>a;

使用者輸入abcd‘Enter‘

執行的過程是,先將abcd輸入到流緩衝區中,然後從緩衝區中輸出到a中。

同樣

cout<<"Enter a number";

執行的過程是,先將"Enter a number."輸入到緩衝區中再從緩衝區中輸出到控制台上來。

由此可見,cin和cout其實並不是我們想象中的相反對立的兩個函數。相反,這兩個函數,其實執行的是同一個過程,都包含輸入和輸出。(前提是在預設情況下)

正是由於這種情況,當我們遇到資料集超大造成 cin TLE的時候,我們可能會認為這是cin的效率不及scanf的原因。其實是輸入緩衝區,flush緩衝區,佔用了時間。

接下來介紹一下,相關的庫函數tie

看看標準庫裡面tie函數的定義,there‘s two overloads,兩重重載。


<1>basic_ostream<char_type,traits_type>* tie() const;

<2>basic_ostream<char_type,traits_type>* tie(basic_ostream<char_type,traits_type>* tiestr); 

第一個重載:returns a pointer to the tied output stream.直接返回一個當前綁定的輸出資料流指標。

第二個重載:ties the object to tiestr and returns a pointer to the stream tied before the call, if any.將當前對象與tiestr流指標綁定,並且返回之前綁定的流指標,如果之前沒有綁定其他流指標,則返回NULL。

兩個重載傳回值都是一個流指標,重載<2>的形參是一個待綁定的流指標。

看下面兩個例子

#01、解除綁定預設的綁定,加快輸入輸出。

比如下面

using namespace std;
void main(){
int i;cin.tie(&cout);cout<<"Enter a number.";
cin>>i;}

使用者輸入3‘Enter‘

代碼執行的過程是,直接將“Enter a number."輸出到控制台上,然後直接將使用者輸入的3讀入到i中。

中間不經過緩衝區。

所以當我們要大量讀取資料的時候可以tie函數解除綁定,來加快資料讀取。

#02、指定綁定輸入輸出資料流,實現不同的輸入輸出功能。

 1 // redefine tied object 2 #include <iostream>      3 #include <fstream>       4 using namespace std; 5 int main() {
6 ostream *prevstr; 7 ofstream ofs; 8 ofs.open("test.txt"); 9 cout << "tie example:\n";10 *cin.tie() << "This is inserted into cout";11 prevstr = cin.tie(&ofs);12 *cin.tie() << "This is inserted into the file";13 cin.tie(prevstr);14 ofs.close();15 return 0;16 }

將標準輸入和檔案輸出綁定。

代碼執行結果:

tie example:
This is inserted into cout

同時產生test檔案

This is inserted into the file

這是因為第一個*cin.tie()等價於cout預設綁定的就是cout。

第二個*cin.tie()等價於ofs。

 

iostream/fstream中的輸入輸出資料流指標的綁定,tie函數的使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.