iostream/fstream中的输入输出流指针的绑定,tie函数的使用

为了兼容c语言的输入输出,c++里面采用tie将输入输出流经行绑定,所以cin/cout并不是独立的。当执行cin时,cout同时会被执行。反之亦然。

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

默认情况下,cin和cout是绑定在一起的,wcin和wcout是绑定在一起的。

也就是说默认情况下,我们执行
 

  1. int a;

  2. 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、指定绑定输入输出流,实现不同的输入输出功能。

// redefine tied object
#include <iostream>     
#include <fstream>      
using namespace std;
int main() {
     ostream *prevstr;
     ofstream ofs;
     ofs.open("test.txt");
     cout << "tie example:\n";
     *cin.tie() << "This is inserted into cout";
     prevstr = cin.tie(&ofs);
     *cin.tie() << "This is inserted into the file";
     cin.tie(prevstr);
     ofs.close();
     return 0;
}

将标准输入和文件输出绑定。

代码执行结果:

tie example:
This is inserted into cout

同时生成test文件

This is inserted into the file

这是因为第一个*cin.tie()等价于cout默认绑定的就是cout。

第二个*cin.tie()等价于ofs。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值