1.list的介绍及使用
1.1 list的介绍
- list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
- list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
- list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。
- 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好
- 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list 的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间 开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这 可能是一个重要的因素)
1.2 list的构造
list() 构造空的list
list(size_type n,const value_type& val = value_type()) 构造的list中包含n个值为val的元素
list(const list& x) 拷贝构造函数
list(InputIterator first,InputIterator last) 用[first,last]区间中的元素构造list
int main()
{
list<int> l1;
list<int> l2(4, 100);
list<int> l3(l2.begin(), l2.end());
list<int> l4(l3);
//以数组为迭代器区间构造l5
int array[] = { 16, 2, 77, 29 };
list<int> l5(array, array + sizeof(array) / sizeof(int));
//用迭代器方式打印l5中的元素
list<int>::iterator it = l5.begin();
while (it != l5.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (auto& e : l5)
{
cout << e << " ";
}
cout << endl;
return 0;
}
运行结果如下:
1.2 list iterator的使用
begin() 返回第一个元素的迭代器
end() 返回最后一个元素下一个位置的迭代器
rbegin() 返回第一个元素的reverse_iterator,即end的位置
rend() 返回最后一个元素下一个位置的reverse_iterator,即begin的位置
cbegin()(C++11) 返回第一个元素的const_iterator
cend()(C++11) 返回最后一个元素下一个位置的const_iterator
crbegin()(C++11) 既crend()的位置
crend()(C++11) 既crbegin()的位置
注意:
- begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动
- rbegin(end)与rend(begin)为反向迭代器,对迭代器执行++操作,迭代器向前移动
- cbegin与cend为const的正向迭代器,与begin和end不同的是:该迭代器指向节点中的元素值不能修改
- crbegin与crend为const的反向得带器,与rbegin和rend不同的是:该迭代器指向节点中的元素值不能修改
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array+sizeof(array) / sizeof(array[0]));
//使用正向迭代器正向打印list中的元素
list<int>::iterator it = l.begin();
while(it != l.end())
{
cout << *it << " ";
++it;
}
cout << endl;
//使用反向迭代器逆向打印list中的元素
list<int>::reverse_iterator rit = l.rbegin();
while (rit != l.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;
//const的正向迭代器
list<int>::const_iterator cit = l.cbegin();
while (cit != l.cend())
{
cout << *cit << " ";
++cit;
}
cout << endl;
return 0;
}
1.2 list的常用接口
void push_front(const value_type& val) 在list首元素前插入值为val的元素
void pop_front() 删除list中的第一个元素
void push_back(const value_type& val) 在list尾部插入值为val的元素
void pop_back() 删除list中最后一个元素
template <class... Args> void emplace_front (Args&&... args) (C++11)在list最后一个元素后根据 参数直接构造元素
template <class... Args> void emplace_back (Args&&... args) (C++11)在list最后一个元素后根据 参数直接构造元素
template <class... Args> iterator emplace( const_iterator position, Args&&... args) (C++11)在链表的任意位置根据参 数直接构造元素
iterator insert (iterator position, const value_type& val) 在list position 位置中插 入值为val的元素
void insert (iterator position, size_type n, const value_type& val) 在list position位置插入n 个值为val的元素
void insert (iterator position, InputIterator first, InputIterator last) 在list position位置插入 [first, last)区间中元素
iterator erase (iterator position) 删除list position位置的 元素
iterator erase (iterator first, iterator last) 删除list中[first, last)区 间中的元素
void swap (list& x) 交换两个list中的元素
void resize (size_type n, value_type val = value_type()) 将list中有效元素个数改变 到n个,多出的元素用val 填充
void clear() 清空list中的有效元素
//push_back/pop_back/push_front/pop_front
void TestList1()
{
int array[] = { 1, 2, 3 };
list<int> L(array, array + sizeof(array) / sizeof(array[0]));
//在list的尾部插入4,头部插入0
L.push_back(4);
L.push_front(0);
PrintList(L);
//删除list尾部节点和头部节点
L.pop_back();
L.pop_front();
PrintList(L);
}
//emplace_back/emplace_front/emplace
class Date
{
public:
Date(int year = 190, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
cout << "Data(int,int,int):" << this << endl;
}
Date(const Date&d)
:_year(d._year)
, _month(d._month)
, _day(d._day)
{
cout << "Data(const Date):" << this << endl;
}
private:
int _year;
int _month;
int _day;
};
// push_back尾插:先构造好元素,然后将元素拷贝到节点中,插入时先调构造函数,再调拷贝构造函数
// emplace_back尾插:先构造节点,然后调用构造函数在节点中直接构造对象
// emplace_back比push_back更高效,少了一次拷贝构造函数的调用
void TestList2()
{
list<Date> l;
Date d(2018, 11, 30);
l.push_back(d);
l.emplace_back(2018, 11, 31);
l.emplace_front(2018, 11, 29);
}
//insert/erase
void TestList3()
{
int array[] = { 1, 2, 3 };
list<int> L(array, array + sizeof(array) / sizeof(array[0]));
//获取链表中第二个节点
auto pos = ++L.begin();;
cout << *pos << endl;
//在pos前插入值为4大的元素
L.insert(pos, 4);
PrintList(L);
//在pos前插入5个值为5的元素
L.insert(pos, 5, 5);
PrintList(L);
//在pos前插入[v.begin(),v.end()]区间中的元素
vector<int> v{ 7, 8, 9 };
L.insert(pos, v.begin(), v.end());
PrintList(L);
//删除pos位置上的元素
L.erase(pos);
PrintList(L);
//删除list中[begin,end]区间中的元素,既删除list中所有的元素
L.erase(L.begin(), L.end());
PrintList(L);
}
//resize/swap/clear
void TestList4()
{
//用数组来构造list
int array[] = { 1, 2, 3 };
list<int> L(array, array + sizeof(array) / sizeof(array[0]));
PrintList(L);
// 将L中元素个数增加到10个,多出的元素用默认值填充
// (注意:如果list中放置的是内置类型,默认值为0, 如果list中放置自定义类型元素,调用缺省构造函数)
L.resize(10);
PrintList(L);
//L中的元素增加到20个,多出的元素用4来填充
L.resize(20, 4);
PrintList(L);
//L中的元素减少到5个
L.resize(5);
PrintList(L);
//用vector中的元素来构造list
vector<int> v{ 4, 5, 6 };
list<int> l(v.begin(), v.end());
PrintList(l);
//交换L和l中的元素
L.swap(l);
PrintList(L);
PrintList(l);
//将l中的元素清空
l.clear();
cout << l.size() << endl;
}
int main()
{
TestList1();
TestList2();
TestList3();
TestList4();
return 0;
}
运行结果如下:
1.2 list的迭代器失效
迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list底层结构为带头节点的双向循坏链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除的时候才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受影响
void TestListIterator1()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
//erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
l.erase(it);
++it;
}
}
//改正
void TestListIterator2()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
l.erase(it++); //it = l.erase(it);
}
}
模拟实现list
代码实现:
#pragma once
#include<iostream>
using namespace std;
namespace zdy
{
template<class T>
struct ListNode
{
T _data;
ListNode<T>* _next;
ListNode<T>* _prev;
ListNode(const T& data = T())
:_data(data)
, _next(nullptr)
, _prev(nullptr)
{}
};
/*List 的迭代器
迭代器有两种实现方式:
1. 原生态指针,比如:vector
2. 将原生态指针进行封装,因迭代器的使用形式与指针完全相同,
因此,在自定义的类中必须实现以下方法:
1. 指针可以解引用,迭代器的类中必须重载operator*()
2. 指针可以通过->访问其所指空间成员,迭代器类中必须重载oprator->()
3. 指针可以++向后移动,迭代器类中必须重载operator++()与operator++(int)
至于operator--() / operator--(int)释放需要重载,
根据具体的结构来抉择,双向链表可以向前移动,所以需要重载,
如果是forward_list就不需要重载 -
4. 迭代器需要进行是否相等的比较,因此还需要重载operator == ()与operator != ()*/
template<class T, class Ref, class Ptr>
struct __ListIterator
{
typedef ListNode<T> Node;
typedef __ListIterator<T, Ref, Ptr> Self;
Node* _node;
__ListIterator(Node* node)
:_node(node)
{}
Ref operator*()
{
return _node->_data;
}
Ptr operator->()
{
//return &(operator*());
return &_node->_data;
}
// ++it; it.operator++(&it)
Self operator++()
{
_node = _node->_next;
return *this;
}
// it++ it.operator++(&it, 0)
Self operator++(int)
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
Self operator--(int)
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}
// it1 != it2
bool operator!=(const Self& it)
{
return _node != it._node;
}
bool operator==(const Self& it)
{
return _node != it._node;
}
};
template<class T>
class List
{
typedef ListNode<T> Node;
public:
typedef __ListIterator<T, T&, T*> iterator;
typedef __ListIterator<T, const T&, const T*> const_iterator;
const_iterator begin() const
{
return const_iterator(_head->_next);
}
const_iterator end() const
{
return const_iterator(_head);
}
iterator begin()
{
return iterator(_head->_next);
}
iterator end()
{
return iterator(_head);
}
List()
:_head(new Node)
{
_head->_next = _head;
_head->_prev = _head;
}
// l2(l1)
List(const List<T>& l)
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
const_iterator it = l.begin();
while (it != l.end())
{
this->PushBack(*it);
++it;
}
}
// l3 = l1
List<T>& operator=(List<T> l)
{
swap(this->_head, l->_head);
return *this;
}
~List()
{
Clear();
delete _head;
_head = nullptr;
}
void Clear()
{
iterator it = begin();
while (it != end())
{
iterator del = it;
++it;
delete del._node;
}
_head->_next = _head;
_head->_prev = _head;
}
void PushBack(const T& x)
{
Insert(end(), x);
}
void PopBack()
{
Erase(--end());
}
void PushFront(const T& x)
{
Insert(begin(), x);
}
void PopFront()
{
Erase(begin());
}
void Insert(iterator pos, const T& x)
{
Node* prev = pos._node->_prev;
Node* newnode = new Node(x);
Node* cur = pos._node;
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
}
iterator Erase(iterator pos)
{
Node* prev = pos._node->_prev;
Node* next = pos._node->_next;
prev->_next = next;
next->_prev = prev;
delete pos._node;
//pos = iterator(prev);
return iterator(next);
}
size_t Size()
{
size_t n = 0;
iterator it = begin();
while (it != end())
{
++n;
++it;
}
return n;
}
bool Empty()
{
return _head == _head->_next;
}
private:
Node* _head;
};
}
测试函数:
#include "List.h"
#include <iostream>
using namespace std;
using namespace zdy;
void Test1()
{
List<int> l;
l.PushBack(1);
l.PushBack(2);
l.PushBack(3);
l.PushBack(4);
List<int>::iterator it = l.begin();
while (it != l.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : l)
{
cout << e << " ";
}
cout << endl;
}
int main()
{
Test1();
return 0;
}
运行结果如下: