C++;List基础概念和使用代码

string类+vector的应用

vector缺陷:如果在其任意位置进行元素插入或删除,需要搬移大量元素;

 


list:底层结构带头结点双向循环链表;链表时间复杂度   O(n);
设置带头节点原因;
1;头插入/头删 操作简便
2;end位置
双向:操作可能以双向移动
循环;找到最后一个节点

list常用的接口;
构造,拷贝和析构
迭代器操作
容量操作
元素访问操作
元素修改操作
特殊操作

//list的使用;
#include<list>
int main()
{
	list<int>L1;
	list<int>L2(10, 5);

	int arr[] = { 1,2,3,4,5,6,7,8,9,0 };
	list<int> L3(arr, arr + sizeof(arr) / sizeof(arr[0]));

	vector<int> v{ 1,2,3,4,5,6,7,8,9,0 };
	list<int> L4(v.begin(), v.end());
	list<int>L5(L3);


	
	//迭代器遍历;
	//遍历list,list不能使用for遍历;
	list<int>::iterator it = L2.begin();
	while (it != L2.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	//反向迭代器;
	list<int>::reverse_iterator rit = L3.rbegin();
	while (rit != L3.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	//使用范围for遍历;
	for (auto e : L4)
		cout << e << " ";
	cout << endl;

	for (auto e : L5)
		cout << e << " ";
	cout << endl;

	system("pause");
	return 0;
}
//list操作;
class Date
{
public:
	Date(int year, int month, int day)
		:_year(year)
		,_month(month)
		,_day(day)
	{}

private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	//list<int>L1(10, 5);
	2(10,3);
	//list<Date>L3( 10,Date(2019, 6, 23));
	L2.resize(20, 8);list<int>L

	auto rit = L2.rbegin();
	while (rit != L2.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	cout << L2.front() << endl;
	cout << L2.back() << endl;
	cout << L2.size() << endl;
	//list<Date>L4(10);

	system("pause");
	return 0;
}
//访问list中任意位置的元素;
//为什么string提供了find;而string和list没有提供find。
//vector和list是线性结构;
int main()
{
	vector<int> v{ 1,2,3,4,5,6,7,8,9,0 };
	cout << v[4] << endl;

	
	auto vit = find(v.begin(), v.end(), 5);
	if (vit != v.end())
	{
		cout << "5 is in vector" << endl;
	}
	else
	{
		cout << "5 is not in vector" << endl;
	}
	
	list<int>L{ 1,2,3,4,5,6,7,8,9,0 };
	auto it = find(L.begin(), L.end(), 5);
	if (it != L.end())
	{
		cout << "5 is in list" << endl;
	}
	else
	{
		cout << "5 is not in list" << endl;
	}
	
	
	system("pause");
	return 0;
}
#endif

 

 

vector和list的区别?

1.底层结构不同;
  vector;动态顺序表;
  list;带头节点双向循环列表

2.vector;支持随机访问;
   list;不支持

3.vector;在插入元素时候,可能需要扩容。list不需要。

4.vector;有与容量相关的操作,list没有。

5.空间利用率不同
   vector
    list;可能造成内存碎片(概率低)(用空间配置器优化);

6.任意位置插入元素的效率不同;
   vector ;   O(N);
   list;    O(1);

7.应用场景不一样;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

童无极

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值