首页 > 移动平台 > 详细

C++中iostream iterator的妙用

时间:2020-06-07 13:37:01      阅读:50      评论:0      收藏:0      [点我收藏+]

  最近刷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 }

C++中iostream iterator的妙用

原文:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13059849.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!