链表list容器中通过splice合并链表与merge的不同,及需要注意的问题

本文通过实例详细介绍了C++标准库中list容器的splice方法的三种使用方式及其效果。splice方法允许开发者将一个链表的部分或全部插入到另一个链表的指定位置,而无需对链表进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"

#include <iostream>

#include <list>

#include <algorithm>

using namespace std;

int_tmain(int argc, _TCHAR* argv[])

{

    list<int> c1,c2,c3,c4;

    c1.push_back(3);

    c1.push_back(6);

    c2.push_back(2);

    c2.push_back(4);

    c3.push_back(5);

    c3.push_back(1);

    c4.push_back(40);

    c4.push_back(41);

    cout<<"c1="<<endl;

    copy(c1.begin(),c1.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"c2="<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    c2.splice(c2.begin(),c1);//将链表c1插入到链表c2的链头:第一种使用方式

    cout<<"After splice c1 and c2>: c2=: "<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"After splice c1 and c2: c1="<<endl;

    copy(c1.begin(),c1.end(),ostream_iterator<int>(cout,""));

    cout<<"可见splice合并后c1中没有内容了"<<endl;

    cout<<"c3="<<endl;

    copy(c3.begin(),c3.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    c2.splice(c2.begin(),c3,c3.begin());//将c3链表的头元素插入c2链表的头部:第二种使用方式

    cout<<"After splice c2 and c3: c2=: "<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"After splice c3="<<endl;

    copy(c3.begin(),c3.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"可见splice后,c3的头元素不在了"<<endl;

    cout<<"c4="<<endl;

    copy(c4.begin(),c4.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    c2.splice(c2.begin(),c4,c4.begin(),c4.end());//将链表c4从开始到结束都合并到c2开始的位置:第三种使用方式

    cout<<"After splice c2 and c4: c2=: "<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"After splice c4="<<endl;

    copy(c4.begin(),c4.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"可见splice合并后c4中没有内容了"<<endl;

   

    return 0;

}

执行结果:

 

可见:splice与merge最大的不同时,不用排序,也不要求原始链表有序。相同点是,被合并的链表或元素将消失。

转载于:https://www.cnblogs.com/pangblog/p/3339498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值