list赋值和交换

1.功能:对list容器进行赋值和交换。

2.函数原型:

  • assign(begin , end); //将[ begin, end)区间中的数据拷贝赋值给本身
  • assign(n , elem); //将n个elem拷贝赋值给本身
  • list &operator = (const list &lst); //重载等号操作符
  • swap(lst); //将list与本身的元素互换
    #include<iostream>
    #include<list>
    using namespace std;
    
    void printlist(const list<int> &L)
    {
    	for(list<int>::const_iterator it=L.begin();it!=L.end();it++)
    		cout<<*it<<" ";
    	cout<<endl;
    }
    void test1()
    {
    	//创建list容器 
    	list<int> L1;
    	
    	//添加数据 
    	L1.push_back(1);
    	L1.push_back(2);
    	L1.push_back(3);
    	L1.push_back(4);
    	printlist(L1); //1 2 3 4
    
    	list<int>L2;
    	L2=L1;
    	printlist(L2); //1 2 3 4
    	
    	list<int>L3;
    	L3.assign(L2.begin(),L2.end());
    	printlist(L3); //1 2 3 4
    	
     
    	list<int>L4;
    	L4.assign(4,6);
    	printlist(L4);  //6 6 6 6
    	
    	
    	cout<<"交换前: "<<endl;
    	printlist(L1); //1 2 3 4
    	printlist(L4);  //6 6 6 6
    	
    	L1.swap(L4);
    	
    	cout<<"交换后: "<<endl;
    	printlist(L1); //6 6 6 6
    	printlist(L4);  //1 2 3 4
    }
    int main()
    {
    	test1();
    	return 0;
     } 

     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值