zoukankan      html  css  js  c++  java
  • C++中iostream iterator的妙用

      最近刷LeetCode会遇到这样的情景:从输入设备读取一串元素,将它们存入vector内后进行处理,最后将这些元素输出。如:

    括号生成(Python and C++解法)

    1  int main() {
    2      Solution s;
    3      for (auto c : s.generateParenthesis(3))
    4          cout << c << " ";  // ((())) (()()) (())() ()(()) ()()()
    5  }

    常见的做法归纳如下:

     1 #include "pch.h"
     2 #include <iostream>
     3 #include <string>
     4 #include <vector>
     5 #include <algorithm>
     6 using namespace std;
     7 
     8 int main() {
     9     string word;
    10     vector<string> text;
    11 
    12     while (cin >> word && word !="0")  // 依次读入单个string
    13         text.push_back(word);
    14 
    15     sort(text.begin(), text.end());
    16 
    17     for (int n = 0; n < text.size(); n++)  // 依次输出单个string,不能直接cout<<text!!!
    18         cout << text[n] << " ";
    19 }

      我们可以使用另一种方法来实现链接内的输出。在标准库定义中,有提供输入输出使用的iostream iterator类,可以实现相同的功能,它使用之前需要先包含iterator头文件,使用时需要一对iterator(first,last)来标识元素的范围。另外,该做法还涉及泛型算法copy的使用,std::copy是C++标准库中的算法接口,主要用于复制,据说其效率要优于for循环逐个复制,且复制过程中不改变元素的顺序。

    上述例子可以改写为如下:

     1 #include "pch.h"
     2 #include <iostream>
     3 #include <string>
     4 #include <vector>
     5 #include <algorithm>
     6 #include <iterator>
     7 
     8 using namespace std;
     9 
    10 int main() {
    11     string word;
    12     vector<string> text;
    13 
    14     while (cin >> word && word != "0")
    15         text.push_back(word);
    16 
    17     sort(text.begin(), text.end());
    18     
    19     ostream_iterator<string> outputos(cout, " "); // 将outputos绑至标准输出
    20     copy(text.begin(), text.end(), outputos);  // copy()会将存在text中的每个元素依次写到由outputos所表示的ostream上输出。
    21 }
  • 相关阅读:
    ExtJS+DWR+Spring+Hibernate开发HRMS(5)
    ExtJS实战(9)疑难杂症分析
    ExtJS实战(8)CRUD+分页+复杂查询+排序
    ExtJS实战(7)登陆
    ExtJS+DWR+Spring+Hibernate开发HRMS(1)
    ExtJS+DWR+Spring+Hibernate开发HRMS(3)
    ExtJS实战(10)项目总结
    ExtJS+DWR+Spring+Hibernate开发HRMS(2)
    Hibernate QBC高级查询
    ExtJS+DWR+Spring+Hibernate开发HRMS(4)
  • 原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13059849.html
Copyright © 2011-2022 走看看