zoukankan      html  css  js  c++  java
  • 使用istream迭代器来输入输出数据

    在C++中,很多人都会选择使用cin来进行数据的输入,使用cout来进行数据的输出,现在在C++11中我们可以使用iostream迭代器来进行这些操作,这会减少代码量,达到的效果和前面两种相同。以下是我学习中的总结,不够完善之处望指导:

    使用istream_iterator来输入数据。

     在我们创建一个流迭代器的时候,必须制定迭代器将要读写的对象类型。

    //以下一般为数据接收的范围
     istream_iterator<int> int_it(cin);//从cin读取int类型的数据
     istream_iterator<int> int_oef;//尾后迭代器

    下面是一个使用istream_iterator来向一个vector中写入string类型数据的例子:

    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        vector<string> vec;
        istream_iterator<string> item_in(cin), eof;//创建istream_iterator迭代器
        while (item_in != eof)//向vec中读入string数据
        {
            vec.push_back(*item_in++);
        }
        cout << "vec中的数据为:" << endl;
        for (auto v : vec)
        {
            cout << v << " ";
        }
        cout << endl;
        system("pause");
        return 0;
    }

    输入:a b v s

    执行结果为:a b v s

    使用ostream_iterator来打印数据

     这里和上面一样我们首先需要创建一个对象,即ostrean_iterator<T> out_iter(cout, " ");里面的第二个参数表示每输出一个数据后面跟上一个空格,第二个参数可以个人设置,这里是代表一下。下面是使用上面的例子和前面学习的sort()和copy(),从标准属兔读取一个整数序列,将其重新排列并将结果输出。

    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        vector<int> vec;
        istream_iterator<int> item_in(cin), eof;
        while (item_in != eof)//使用流输入输入数据
        {
            vec.push_back(*item_in++);
        }
        cout << "vec中的数据为:" << endl;
        for (auto v : vec)
        {
            cout << v << " ";
        }
        cout << endl;
            //将vec中的数据按照字典的顺序进行重新排列
        sort(vec.begin(), vec.end());
            //定义流输出迭代器,每个数据后跟一个空格
        ostream_iterator<int> out_iter(cout, " ");
            //使用copy和流输出输出数据
        copy(vec.cbegin(), vec.cend(), out_iter);
        system("pause");
        return 0;
    }

    输入:1 2 4 3 5 7 6

    执行结果为:1 2 3 4 5 6 7

    从上面的两句话可以看出来,使用istream迭代器输入输出数据可以达到和cin、cout同样的效果,但是前者明显可以减少很多代码。

  • 相关阅读:
    Android中Context具体解释 ---- 你所不知道的Context
    JDK6、Oracle11g、Weblogic10 For Linux64Bit安装部署说明
    matplotlib 可视化 —— 定制 matplotlib
    matplotlib 可视化 —— 移动坐标轴(中心位置)
    matplotlib 可视化 —— 移动坐标轴(中心位置)
    matplotlib 可视化 —— 定制画布风格 Customizing plots with style sheets(plt.style)
    matplotlib 可视化 —— 定制画布风格 Customizing plots with style sheets(plt.style)
    指数函数的研究
    指数函数的研究
    指数分布的研究
  • 原文地址:https://www.cnblogs.com/pengjun-shanghai/p/4861568.html
Copyright © 2011-2022 走看看