STL Iterator - insertion iterators
介绍
C++ STL的插入迭代器只是构建一个插入迭代器,具体的插入工作是通过调用容器本身的插入函数完成的,一般会配合copy算法完成插入工作。
(1) back_inserter
Construct back insert iterator
template <class Container>
back_insert_iterator<Container> back_inserter (Container& x);
容器x必须要有push_back成员函数,如STL中的vector, deque and list
(2) inserter
Construct insert iterator
template <class Container, class Iterator>
insert_iterator<Container> inserter (Container& x, Iterator it);
- 容器
x必须要有insert成员函数,如STL中的vector, deque and list it是指向待插入目标容器x的位置的iterator
(3) front_inserter
Constructs front insert iterator
template <class Container>
front_insert_iterator<Container> front_inserter (Container& x);
- 容器
x必须要有push_front成员函数,如STL中的deque and list
Examples
#include <iostream>
#include <vector>
#include <algorithm>
#include <list>
using namespace std;
int main(){
vector<int> c1 = { 1, 2, 3, 4, 5};
vector<int> c2 = {10, 20, 30, 40, 50};
/* back_inserter */
copy(c2.begin(), c2.end(), back_inserter(c1));
for(auto &it: c1){
cout << it << " ";
}
cout << endl;
// Output: 1 2 3 4 5 10 20 30 40 50
/* inserter */
auto insert_it = c1.begin();
// equal to insert_it = insert_it + 3
advance(insert_it, 3);
copy(c2.begin(), c2.end(), inserter(c1, insert_it));
for(auto &it: c1){
cout << it << " ";
}
cout << endl;
// Output: 1 2 3 10 20 30 40 50 4 5 10 20 30 40 50
/* inserter */
list<char> L1 = {'a', 'b', 'c'};
list<char> L2 = {'d', 'e', 'f'};
copy(L2.begin(), L2.end(), front_inserter(L1));
for(auto &it: L1){
cout << it << " ";
}
cout << endl;
// Output: f e d a b c
return 0;
}

浙公网安备 33010602011771号