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 }

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++中iostream iterator的妙用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/353486

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午8:06
下一篇 2023年3月2日 上午8:06

相关推荐