您的位置:首页 > 移动开发 > IOS开发

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

2017-01-08 14:48 246 查看
为了兼容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、指定绑定输入输出流,实现不同的输入输出功能。

// 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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐