zoukankan      html  css  js  c++  java
  • STL之--插入迭代器(back_inserter,inserter,front_inserter的区别)

    除了普通迭代器,C++标准模板库还定义了几种特殊的迭代器,分别是插入迭代器、流迭代器、反向迭代器和移动迭代器,定义在<iterator>头文件中,下面主要介绍三种插入迭代器(back_inserter,inserter,front_inserter)的区别。
    首先,什么是插入迭代器?插入迭代器是指被绑定在一个容器上,可用来向容器插入元素的迭代器。
    back_inserter:创建一个使用push_back的迭代器
    inserter:此函数接受第二个参数,这个参数必须是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前。
    front_inserter:创建一个使用push_front的迭代器(元素总是插入到容器第一个元素之前)
    由于list容器类型是双向链表,支持push_front和push_back操作,因此选择list类型来试验这三个迭代器。

     1 #include <iterator>
     2 #include <list>
     3 #include <iostream>
     4 
     5 using namespace std;
     6 
     7 void listprint(list<int> lst) {
     8     if (lst.empty())
     9         return;
    10     while (!lst.empty()) {
    11         cout << lst.front() << " ";
    12         lst.pop_front();
    13     }
    14     cout << endl;
    15 }
    16 
    17 int main() {
    18     list<int> lst = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    19     list<int> lst2 = { 10 }, lst3 = { 10 }, lst4 = { 10 };
    20     copy(lst.cbegin(), lst.cend(), back_inserter(lst2));
    21     //lst2包含10,1,2,3,4,5,6,7,8,9
    22     listprint(lst2);
    23     copy(lst.cbegin(), lst.cend(), inserter(lst3, lst3.begin()));
    24     //lst3包含1,2,3,4,5,6,7,8,9,10
    25     listprint(lst3);
    26     copy(lst.cbegin(), lst.cend(), front_inserter(lst4));
    27     //lst4包含9,8,7,6,5,4,3,2,1,10
    28     listprint(lst4);
    29     return 0;
    30 }

    结果:

    注意:

    inserter方法:

      通过inserter在it指定位置之前插完一个数值后,插入迭代器it仍会指向原来的位置,相当于调用了:

    it= list2.insert(it,val);
    ++it;
    (参考C++primer 第五版 p358)

      list2为空列表,由inserter返回的插入迭代器指向不存在的end,所以等效在end前依次添加了:1,2,3,4

    back_inserter和front_inserter方法都是以容器为参数传递进去,然后再去调用容器的相应头部或尾部插入方法。

    本文来自博客园,作者:Mr-xxx,转载请注明原文链接:https://www.cnblogs.com/MrLiuZF/p/14090724.html

  • 相关阅读:
    python import模块的搜索路径
    【转载】PDB命令行调试Python代码
    python 操作hdfs
    hadoop基本命令
    配置hadoop集群
    hadoop配置
    pycharm 配置spark
    pip 使用镜像下载第三方包
    pyechart.Geo -- 基于中国地图数据显示
    cv2 读取图片及展示
  • 原文地址:https://www.cnblogs.com/MrLiuZF/p/14090724.html
Copyright © 2011-2022 走看看