C++-STL(2)-list-增删改-去重-合并-交换

     list的特点是存储地址不连续,所以添加、删除快,访问慢。
     list作为容器的一种,双向链表,基本用法就是构造、插入(头、尾、任意位置)、删除、修改,高级一点的就是合并、交换、排序。 


    

  基本操作
 

/*
1.构造
2.遍历
3.头尾插入
4.删除(按值、头尾)
5.去连续重复的值
*/
void myListOne_int(void)
{
	list<int> l1;               //空
	list<int> l2(5);            //list(N)         N个0
	list<int> l3(5, 1);         //list(n, elem); n 个 elem 拷贝给本身
	                            //list(begin,end)
	
	//1.构造 不是固定大小,先初始化一个大小 数组构造
	int arr[] = { 1,2,3,4,5,6,7,8,9 };
	int* end = arr + sizeof(arr) / sizeof(arr[0]);
	list <int>l_test(arr, end);

	//2.遍历
	list <int>::iterator it;
	/*for (it = l_test.begin(); it !=l_test.end(); ++it)
	{
		cout << *it << endl;
	}*/
	//3.从头、尾插入  
	list<int> l_test2;
	l_test2.push_back(1);
	l_test2.push_back(2);
	l_test2.push_back(3);
	l_test2.push_back(4);
	l_test2.push_back(5);
	l_test2.insert(l_test2.begin(), 100);      //在l_test2的开始位置(即头部)插入100
	l_test2.insert(l_test2.end(), 2, 100);     //在l_test2的结束位置插入2个100
	/*l_test2.push_front(1);
	l_test2.push_front(2);
	l_test2.push_front(3);
	l_test2.push_front(4);
	l_test2.push_front(5);*/
	
	/*for (it = l_test2.begin(); it != l_test2.end(); ++it)
	{
		cout << *it << endl;
	}*/
	//4.按值删除 
//	l_test2.remove(3);
//	l_test2.erase(l_test2.begin());  //将a的第一个元素删除
//	l_test2.pop_back();
//	l_test2.pop_front();
	/*for (it = l_test2.begin(); it != l_test2.end(); ++it)
	{
		cout << *it << endl;
	}*/
	//5.去重 连续重复的值
	int arr3[] = { 1,2,3,4,5,5,5,5,6,7,9,9,5,5 };
	int* end3 = arr3 + sizeof(arr3) / sizeof(arr3[0]);
	list <int>l_test3(arr3, end3);
	for (it = l_test3.begin(); it != l_test3.end(); ++it)
	{
		cout << *it << endl;
	}
		cout << "*****************"<< endl; 

	l_test3.unique();

	for (it = l_test3.begin(); it != l_test3.end(); ++it)
	{
		cout << *it << endl;
	}



}


  复杂一点的操作
 

6.替换assign() a.assign(n, val):将a中的所有元素替换成n个val元素
		list<int>b{1,2,3,4,5};
		b.assign(5,10);
		b中的元素变为10, 10, 10, 10, 10

	a.assign(b.begin(), b.end())
	list<int>a{6,7,8,9};
	list<int>b{1,2,3,4,5};
	b.assign(a.begin(),a.end());
	b中的元素变为6,7,8,9

7.两个列表交换 swap()
			   list<int>a{6,7,8,9};
			   list<int>b{1,2,3,4,5};
			   swap(a, b);
8.逆置
		  list<int>b{1,2,3,4,5};
		  reverse(b.begin(),b.end();
	   b中元素变为5,4,3,2,1
9.合并merge()
		list<int>a{6,7,8,9};
		list<int>b{2, 1, 3, 6, 5};
		a.merge(b,greater<int>());  2,1,3,6,5,6,7,8,9

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值