list容器封装的是双向循环列表
功能:将数据进行链式存储
链表:是一种物理储存单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的。
链表的组成:链表由一系列节点组成。
节点的组成:一个是存储数据元素的数据域,另一个是存储下一个节点地址的指针域
由于链表的储存方式并不是连续的内存空间,因此链表中的迭代器只能支持前移和后移,属于双向迭代器。
list的优点:
1.采用动态储存分配,不会造成内存浪费和溢出
2.链表执行插入和删除操作十分方便,修改指针即可,不需要移动大量元素。
list的缺点:
1.链表灵活,但是空间(指针域)和时间(遍历)额外耗费较大
list有一个重要的性质,插入操作和删除操作都不会造成原有list迭代器的失效,这在vector,deque等都是都是不成立的
list和vector是两个最常用的容器,各有优缺点
list构造函数
void print(const list<int>& L)
{
for (list<int>::const_iterator it = L.begin(); it != L.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
list<int>L;
for (int i = 1; i <= 10; i++)
{
L.push_back(i);
}
print(L);//1 2 3 4 5 6 7 8 9 10
list<int>L2(L.begin(), L.end());
print(L2);//1 2 3 4 5 6 7 8 9 10
list<int>L3(10, 100);
print(L3);//100 100 100 100 100 100 100 100 100 100
list<int>L4(L3);
print(L4);//100 100 100 100 100 100 100 100 100 100
}
list赋值和交换
void test01()
{
list<int>L;
for (int i = 1; i <= 10; i++)
{
L.push_back(i);
}
print(L);//1 2 3 4 5 6 7 8 9 10
list<int>L2;
L2.assign(L.begin(), L.end());
print(L2);//1 2 3 4 5 6 7 8 9 10
list<int>L3;
L3.assign(10, 100);
print(L3);//100 100 100 100 100 100 100 100 100 100
list<int>L4;
L4 = L3;
print(L4);//100 100 100 100 100 100 100 100 100 100
L4.swap(L);
print(L4);//1 2 3 4 5 6 7 8 9 10
print(L);//100 100 100 100 100 100 100 100 100 100
}
list大小操作:
void test01()
{
list<int>L;
for (int i = 1; i <= 10; i++)
{
L.push_back(i);
}
print(L);//1 2 3 4 5 6 7 8 9 10
if (!L.empty())
{
cout << "容器不为空"<<endl;
}
cout << "容器内元素的个数为:" << L.size() << endl;
}
成员函数reszie(num);和重载版本resize(num,elem)老演员了,就不写了
list的插入和删除
push_back();在容器尾部加入一个元素
pop_back();删除容器中最后一个元素
push_front();在容器头部插入一个元素
pop_front();从容器开头删除第一个元素
insert();
clear();
erase();
remove();
也都是老演员了,这里就不多赘述了;
list数据存储
front();返回容器第一个元素;
back():返回容器最后一个元素
list反转和排序:
reverse();反转列表
sort();链表排序
bool cmp(int a, int b)
{
return a > b;
}
void test01()
{
list<int>L;
for (int i = 1; i <= 10; i++)
{
L.push_back(i);
}
print(L);//1 2 3 4 5 6 7 8 9 10
L.reverse();
print(L);//10 9 8 7 6 5 4 3 2 1
list<int>L2;
L2.push_back(4);
L2.push_back(6);
L2.push_back(3);
L2.push_back(8);
L2.push_back(4);
L2.push_back(1);
L2.sort();
print(L2);//1 3 4 4 6 8,默认升序排序
L2.sort(cmp);
print(L2);//8 6 4 4 3 1
}
注意:这里的sort是成员函数。