功能描述:
- 给list容器进行赋值,以及交换list容器
函数原型:
- assign(beg,end); //将[beg,end)区间中的数据拷贝赋值给本身。
- assign(n,elem); //将n个elem拷贝赋值给本身
- list& operator=(const list &lst); //重载等号操作符
- swap(lst); //将lst与本身的元素互换
源码展示:
#include<iostream>#include<list>using namespace std;//list容器的赋值和交换void printList(const list<int>& L) {for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {cout << *it << " ";}cout << endl;}//赋值void test01() {//创建list容器list<int>L1;//默认构造//添加数据L1.push_back(10);L1.push_back(20);L1.push_back(30);L1.push_back(40);//遍历容器printList(L1);list<int>L2;L2 = L1;//operator = 赋值printList(L2);list<int>L3;L3.assign(L1.begin(), L1.end());//区间赋值printList(L3);list<int>L4;L4.assign(10,1000);//区间赋值printList(L4);}//交换void test02() {//创建list容器list<int>L1;//默认构造//添加数据L1.push_back(10);L1.push_back(20);L1.push_back(30);L1.push_back(40);list<int>L2;L2.assign(10, 1000);//区间赋值cout << "交换前:" << endl;printList(L1);printList(L2);L1.swap(L2);cout << "交换后:" << endl;printList(L1);printList(L2);}int main() {test01();test02();return 0;}
运行结果:
