copy函数与back_inserter、inserter、front_inserter三个迭代器

copy下面程序使用vscode跑的,能直接用。一运行就懂了。

干的事情是把lst里的内容拷贝到lst2、lst3、lst4中。使用不同的迭代器会有不同的效果

back_inserter和front_inserter根据名字就能理解,尾插法和头插法

  • lst2使用尾插法,lst中每个元素都插在了lst2点末尾,而且保持了正序。
  • lst4是头插法,lst每个元素都插在lst4的前面,插完变成倒序了

lst3的inserter,注意需要两个参数。此函数接受第二个参数,这个参数必须是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前。(本来想试一试把lst3.begin改成其他位置,但是,list类型里面迭代器不能加减,也不能使用下标运算符[ ],于是我就不知道应该怎么修改位置了)

#include <iostream>
#include <iterator>
#include <list>
using namespace std;

int main() 
{
    list<int> lst = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    list<int> lst2 ={10}, lst3={10},lst4={10};

    //lst2包含10,1,2,3,4,5,6,7,8,9
    copy(lst.cbegin(), lst.cend(), back_inserter(lst2));
    for (auto i : lst2)
    {
        cout << i << ' ';
    }
    cout << endl;

    //lst3包含1,2,3,4,5,6,7,8,9,10
    copy(lst.cbegin(), lst.cend(), inserter(lst3, lst3.begin()));
    for (auto i : lst3)
    {
        cout << i << ' ';
    }
    cout << endl;

    //lst4包含9,8,7,6,5,4,3,2,1,10
    copy(lst.cbegin(), lst.cend(), front_inserter(lst4));
    for (auto i : lst4)
    {
        cout << i << ' ';
    }
    cout << endl;
    

    system("pause");
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值