定义:
插入器有三种类型,差异在于元素插入的位置:
假设iter是一个插入迭代器,则
tips: 只有在容器支持push_front的情况下,才能使用front_inserter。同样,只有容器支持push_back的情况下,才能使用back_inserter。
代码演示:
#include<iostream>
#include<list>
#include<algorithm>
using namespace std;
void test()
{
list<int> lst = { 1,2,3,4 };
list<int> lst1, lst2;
auto iter_back = back_inserter(lst1);
auto iter_front = front_inserter(lst2);
//写法1:
*iter_back = 520;//等价于lst1.push_back(520)
cout << lst1.front() << endl;
lst1.pop_front();
//写法2:
iter_back = 521;//等价于lst1.push_back(521)
cout << lst1.front() << endl;
//注意:写法1和写法2等价的原因是*it,++it和it++不会对it做任何事情
//下面统一用写法2:
//注意:我们使用front_inserter总是插入到容器第一个元素之前
iter_front = 1;
iter_front = 2;
iter_front = 3;
for_each(lst2.begin(), lst2.end(), [](int val) {cout << val << " "; });
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}
结合copy算法演示
#include<iostream>
#include<list>
#include<algorithm>
using namespace std;
void test()
{
list<int> lst = { 1,2,3,4 };
list<int> lst1, lst2;
auto iter_back = back_inserter(lst1);
auto iter_front = front_inserter(lst2);
lst1.push_back(520);
lst2.push_back(520);
copy(lst.begin(), lst.end(), iter_back);
copy(lst.begin(), lst.end(), iter_front);
cout << "调用iter_back后lst1= ";
for_each(lst1.begin(), lst1.end(), [](int val) {cout << val << " "; });
cout << endl;
cout << "调用iter_front后lst2= ";
for_each(lst2.begin(), lst2.end(), [](int val) {cout << val << " "; });
cout << endl;
}
int main()
{
test();
system("pause");
return 0;
}