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; }