目录
一、list介绍与使用
1.1 list介绍
①list底层是带头双向循环链表,在任意位置可进行插入和删除的序列式容器。
②list与其他序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好。
③与其他序列式容器相比,list的缺陷是不支持任意位置的随机访问,要访问某个元素,必须从已知位置迭代到访问位置,这段迭代则需要额外的线性时间开销,途中,还需要开辟额外空间,来保存每个节点的相关联信息。
1.2 list的使用
list同样也是一个模板类,有了前面的string、vector基础,这里也不在对list的接口做过多解释,而是简单的进行介绍使用一些常见的重要接口,然后再来对其底层进行一个分析与模拟实现。
1.2.1list的构造
构造函数 | 接口说明 |
list(size_type n,const value_type& val = value_type()) | n个val值构造list |
list() | 构造空list |
list(const list& x) | 拷贝构造 |
list(InputIterator first,InputIterator last) | 用[first,last)区间中的元素构造list |
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> lt1;//构造空list
list<double> lt2(3, 2.1);//用3个2.1值构造lt2
for (auto e : lt2)
{
cout << e << " ";
}
cout << endl;
list<double> lt3(lt2);//拷贝构造,用lt2构造lt3
for (auto e : lt3)
{
cout << e << " ";
}
cout << endl;
list<double> lt4(lt3.begin(), lt3.end());//用迭代器区间中的元素构造lt4
for (auto e : lt4)
{
cout << e << " ";
}
cout << endl;
return 0;
}
1.2.2iterator
函数声明 | 接口说明 |
begin+end | 返回第一个元素的迭代器+返回最后一个元素的下一个位置的迭代器 |
rbegin+rend | 返回第一个元素的reverse_iterator,即最后一个元素的下一个位置+返回最后一个元素的reverse_iterator,即第一个元素的位置 |
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<char> ch(5,'a');
list<char>::iterator cit = ch.begin();
list<char>::reverse_iterator rcit = ch.rbegin();
while (cit != ch.end())
{
cout << *cit;
cit++;
}
cout << endl;
while (rcit != ch.rend())
{
cout << *rcit;
rcit++;
}
return 0;
}
1.2.3容量
函数声明 | 接口说明 |
empty | 检测list是否为空,是返回true,否返回false |
size | 返回list中有效节点的个数 |
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<char> ch(5, 'a');
cout << boolalpha<< ch.empty() << endl;//以bool类型的方式打印,而不是以数字方式
cout << ch.size() << endl;
return 0;
}
1.2.4元素访问
函数声明 | 接口说明 |
front | 返回list的第一个节点值的引用 |
back | 返回list的最后一个节点值的引用 |
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<string> ch(5,"a");
cout << ch.front() << endl;
cout << ch.back() << endl;
return 0;
}
1.2.5 元素修改
函数声明 | 接口说明 |
push_front | 头插,在list首元素插入一个值 |
pop_front | 头删,删除list首元素 |
push_back | 尾插,在尾 |