迭代器之配接器

一、Insert Iterators(安插型迭代器)

  • back_inserter(container)
  • front_inserter(container)
  • inserter(container, pos)  使用insert()在pos位置上安插元素,元素排列顺序和安插顺序相同
 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <deque>
 5 #include <set>
 6 #include <algorithm>
 7 
 8 using namespace  std;
 9 
10 int main()
11 {
12     list<int> coll1;
13     
14     for (int i=1; i<=9; ++i) {
15     coll1.push_back(i);
16     }
17     
18     vector<int> coll2;
19     copy(coll1.begin(), coll1.end(), back_inserter(coll2));
20     
21     deque<int> coll3;
22     copy(coll1.begin(), coll1.end(), front_inserter(coll3));
23     
24     set<int> coll4;
25     copy(coll1.begin(), coll1.end(), inserter(coll4, coll4.end()));
26     set<int>::const_iterator pos;
27     for(pos=coll4.begin(); pos != coll4.end(); ++pos) {
28     cout << * pos << " ";
29     }
30     cout << endl;
31 }
View Code

二、Stream Iterators (流迭代器)

  • istream_iterator<T> in(istrm) 从输入流中读入
  • ostream_iterator<T> os(ostrm, delim) 读出到输出流 ostrm中,以delim作为分隔符

注:istream_iterator<T> eof 中,eof 为空的istream_iterator对象,用作结束迭代器。绑在流上的迭代器遇到文件结束符或某个error时,将等于结束迭代器的值

 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <deque>
 5 #include <set>
 6 #include <algorithm>
 7 #include <string>
 8 // #include <ios>
 9 #include <iterator>
10 
11 using namespace  std;
12 
13 int main()
14 {
15    vector<string> coll;
16    
17    copy(istream_iterator<string>(cin),
18     istream_iterator<string>(),
19     back_inserter(coll));
20    
21 //    sort(coll.begin(), coll.end());
22    
23    unique_copy(coll.begin(), coll.end(),
24            ostream_iterator<string>(cout, " "));
25 }
View Code

三、Reverse Iterators(逆向迭代器)

  • rbegin()
  • rend()
 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <deque>
 5 #include <set>
 6 #include <algorithm>
 7 #include <string>
 8 // #include <ios>
 9 #include <iterator>
10 
11 using namespace std;
12 
13 int main()
14 {
15     vector<int> coll;
16     
17     for(int i=1; i<=9; ++i) {
18     coll.push_back(i);
19     }
20     
21     copy(coll.rbegin(), coll.rend(),
22      ostream_iterator<int>(cout, " "));
23     cout << endl;
24     
25     copy(coll.begin(), coll.end(),
26      ostream_iterator<int>(cout, " "));
27     cout << endl;
28     return 0;
29 }
View Code

 

posted on 2013-06-07 18:28  K's Blog  阅读(195)  评论(0编辑  收藏  举报

导航