list容器之赋值和交换

2021-03-02 15:39:38 浏览数 (1)

赋值和交换

函数原型:

代码语言:javascript复制
#include<iostream>
using namespace std;
#include<list>
void print(list<int>& L)
{
	for (list<int>::iterator it = L.begin(); it != L.end(); it  )
	{
		cout << *it << " ";
	}
	cout << endl;
}
//list的赋值和交换
void test()
{
	//默认构造
	list<int> L1 = {5,2,0,1};
	L1.push_back(3);
	L1.push_back(1);
	L1.push_back(4);
	print(L1);

	//operator=赋值
	list<int> L2;
	L2 = L1;
	print(L2);
    
	//区间的元素赋值给本身
	list<int> L3;
	L3.assign(L1.begin(), L1.end());
	print(L3);

	//n个elem
	list<int> L4;
	L4.assign(5, 100);
	print(L4);

	//交换L3和L4
	cout << "交换后:" << endl;
	L3.swap(L4);
	cout << "L3:";
	print(L3);
	cout << "L4: ";
	print(L4);
}
int main()
{
	test();
	system("pause");
	return 0;
}

0 人点赞