#include<iostream>
#include<vector>
#include<list>
#include<iterator>
usingnamespace std;
template<typename T>
voidPrintElements(T c)
{
typename T::const_iterator itr = c.begin();//在GCC下typename不能省略
while(itr != c.end())
{
cout <<*itr++<<" ";
}
cout << endl;
}
int main()
{
vector<int> vecSrc;
list<int> vecDest;
for(vector<int>::size_type i =0; i <3;++i)
{
vecSrc.push_back(i);
}//--0,1,2---
/**
* 第一种方法是调用<iterator>头文件中的函数来返回一个back_insert_iterator对象
* template< class Container >
* std::back_insert_iterator<Container> back_inserter( Container& c );
*/
/**
* 第二种方法是调用back_insert_iterator类的构造函数来创建类对象
* explicit
* back_insert_iterator(_Container& __x) : container(&__x) { }
*/
copy(vecSrc.begin(), vecSrc.end(), back_inserter(vecDest));
//copy(vecSrc.begin(), vecSrc.end(), back_insert_iterator<list<int> >(vecDest));
PrintElements(vecDest);//--0,1,2---
copy(vecSrc.begin(), vecSrc.end(), front_inserter(vecDest));
//copy(vecSrc.begin(), vecSrc.end(), front_insert_iterator<list<int> >(vecDest));
PrintElements(vecDest);//--2,1,0,0,1,2---
copy(vecSrc.begin(),vecSrc.end(), inserter(vecDest,++vecDest.begin()));
//copy(vecSrc.begin(), vecSrc.end(), insert_iterator<list<int> >(vecDest, ++vecDest.begin()));
PrintElements(vecDest);//--2,0,1,2,1,0,0,1,2---
back_insert_iterator<list<int>> itBack = back_inserter(vecDest);//这里也可以直接调用构造函数
*itBack =101;
*itBack =102;//itBack每次都指向容器最后的元素
PrintElements(vecDest);//.....101,102
front_insert_iterator<list<int>> itFront = front_insert_iterator<list<int>>(vecDest);
*itFront =1001;
*itFront =1002;
PrintElements(vecDest);//1002,1001......
insert_iterator<list<int>> itIst = inserter(vecDest, vecDest.begin());
*itIst =11;
*itIst =12;
PrintElements(vecDest);//--11,12,1002,1001.....
// *itIst = value;相当于
// itIst = c.insert(it,value);
// ++itIst;
// insert函数返回的是指向插入元素的迭代器,由于该函数是在给定迭代器之前插入元素,所以++itIst之后
// itIst依然指向的是原来的元素。操作结束后itIst指向的位置未发生改变
return0;
}