C++中insert iterator/iostream iterator的使用方法(详细)

1. C++的insert iterators, 可以将一般迭代器的赋值操作转变为插入操作,这样的迭代器包括

(1)专司尾端插入操作的back_insert_iterator,对应于STL函数back_inserter(),要求容器自身支持push_back操作;

(2)专司头端插入操作的front_insert_iterator,对应于STL函数front_inserter(),要求容器自身支持push_front操作;

(3)可从任意位置执行插入操作的insert_iterator,对应于STL函数inserter(),要求容易自身支持insert操作;

2. C++的iostream iterators,可以将迭代器绑定到某个iostream对象身上,包括:

(1)绑定到istream对象身上的istream_iterator,拥有输入功能;

(2)绑定到ostream对象身上的ostream_iterator,拥有输出功能;

3. 以下是这两大迭代器的用法举例

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
using namespace std;
 
int main(void)
{
    vector<int> vecs;
    list<int> ls, ls1, ls2, ls3;
 
    ostream_iterator<int> outite(cout, " ");
    istream_iterator<int> inite(cin), eof;
    while(inite != eof)
    {
        vecs.push_back(*inite++);
    }
    copy(vecs.cbegin(), vecs.cend(), outite);
    cout << endl;
 
    back_inserter(ls) = 1;
    back_inserter(ls) = 2;
 
    front_inserter(ls) = 3;
    front_inserter(ls) = 4;
 
    inserter(ls, ls.begin()) = 5;
    inserter(ls, ls.end()) = 6;
 
    back_insert_iterator<list<int> > backIter(ls);
    *backIter = 7;
    *backIter = 8;
 
    front_insert_iterator<list<int> > frontIter(ls);
    *frontIter = 9;
    *frontIter = 10;
 
    insert_iterator<list<int> > insertIter(ls, ls.begin());
    *insertIter = 11;
    *insertIter = 12;
 
    copy(ls.cbegin(), ls.cend(), outite);
    cout << endl;
 
    copy(ls.cbegin(), ls.cend(), front_inserter(ls1));
    copy(ls1.cbegin(), ls1.cend(), outite);
    cout << endl;
 
    copy(ls.cbegin(), ls.cend(), back_inserter(ls2));
    copy(ls2.cbegin(), ls2.cend(), outite);
    cout << endl;
 
    copy(ls.cbegin(), ls.cend(), inserter(ls3, ls3.begin()));
    copy(ls3.cbegin(), ls3.cend(), outite);
    cout << endl;
 
    return 0;
}
 

 

posted @ 2020-07-19 10:15  Mr-xxx  阅读(436)  评论(0编辑  收藏  举报