C++之插入迭代器

时间:2022-07-03 21:40:21
  1. #include<iostream>
  2. #include<vector>
  3. #include<list>
  4. #include<iterator>
  5. usingnamespace std;
  6. template<typename T>
  7. voidPrintElements(T c)
  8. {
  9. typename T::const_iterator itr = c.begin();//在GCC下typename不能省略
  10. while(itr != c.end())
  11. {
  12. cout <<*itr++<<" ";
  13. }
  14. cout << endl;
  15. }
  16. int main()
  17. {
  18. vector<int> vecSrc;
  19. list<int> vecDest;
  20. for(vector<int>::size_type i =0; i <3;++i)
  21. {
  22. vecSrc.push_back(i);
  23. }//--0,1,2---
  24. /**
  25. * 第一种方法是调用<iterator>头文件中的函数来返回一个back_insert_iterator对象
  26. * template< class Container >
  27. * std::back_insert_iterator<Container> back_inserter( Container& c );
  28. */
  29. /**
  30. * 第二种方法是调用back_insert_iterator类的构造函数来创建类对象
  31. * explicit
  32. * back_insert_iterator(_Container& __x) : container(&__x) { }
  33. */
  34. copy(vecSrc.begin(), vecSrc.end(), back_inserter(vecDest));
  35. //copy(vecSrc.begin(), vecSrc.end(), back_insert_iterator<list<int> >(vecDest));
  36. PrintElements(vecDest);//--0,1,2---
  37. copy(vecSrc.begin(), vecSrc.end(), front_inserter(vecDest));
  38. //copy(vecSrc.begin(), vecSrc.end(), front_insert_iterator<list<int> >(vecDest));
  39. PrintElements(vecDest);//--2,1,0,0,1,2---
  40. copy(vecSrc.begin(),vecSrc.end(), inserter(vecDest,++vecDest.begin()));
  41. //copy(vecSrc.begin(), vecSrc.end(), insert_iterator<list<int> >(vecDest, ++vecDest.begin()));
  42. PrintElements(vecDest);//--2,0,1,2,1,0,0,1,2---
  43. back_insert_iterator<list<int>> itBack = back_inserter(vecDest);//这里也可以直接调用构造函数
  44. *itBack =101;
  45. *itBack =102;//itBack每次都指向容器最后的元素
  46. PrintElements(vecDest);//.....101,102
  47. front_insert_iterator<list<int>> itFront = front_insert_iterator<list<int>>(vecDest);
  48. *itFront =1001;
  49. *itFront =1002;
  50. PrintElements(vecDest);//1002,1001......
  51. insert_iterator<list<int>> itIst = inserter(vecDest, vecDest.begin());
  52. *itIst =11;
  53. *itIst =12;
  54. PrintElements(vecDest);//--11,12,1002,1001.....
  55. // *itIst = value;相当于
  56. // itIst = c.insert(it,value);
  57. // ++itIst;
  58. // insert函数返回的是指向插入元素的迭代器,由于该函数是在给定迭代器之前插入元素,所以++itIst之后
  59. // itIst依然指向的是原来的元素。操作结束后itIst指向的位置未发生改变
  60. return0;
  61. }