istream_iterators VS ostream_iterators的区别

istream_iterators

 ostream_iterators

区别1:

 *in返回的是一个右值,即我们无法通过istream_iterators对输入流本身进行修改

out返回的是一个左值,即我们可以写入到ostream中去 

区别2:

In的++ operator是有意义的,我们可以通过++,对流进行枚举:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iterator>
 
using namespace std; 
 
int main()
{
    string filename("2.txt"); 
    fstream fs(filename, std::ios::in);
    
    if (!fs.is_open()) {
        std::cout << "Failed to open the file." << std::endl;
        return 1;
    }
 
    istream_iterator<int> in1(fs),eof;
 
 
    cout << "output the file content" << endl; 
    
    for (istream_iterator<int> beg1=in1; beg1 != eof; beg1++)
    {
        cout <<* beg1 << endl;
    }
   
    fs.close(); 
}

out的*和++定义成了,不会做任何操作,即在我们每次使用out对输出流进行操作的时候, out会自动实现自加的操作,可以想象是因为,插入了一个元素,out的位置自动向后移动,例如:

 vector<int> sample{ 1,2,3,4,5 };
    ostream_iterator<int> ou(cout, " ");
    cout << "output the vector sample via ou: " << endl;
    for (auto& element : sample)
    {
        *ou++ = element;
    }

它的效果和下面这段是一样的: 

for (auto& element : sample)
    {
        ou = element;
    }

输出:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值