文章目录
前言
在 C++ STL(标准模板库)中,List
是一个带头双向链表,可以存储多个元素并且支持动态调整大小,适合频繁插入和删除操作;而 Vector
是一个动态数组,元素在内存中是连续存储的,适合需要快速随机访问的场景。List
提供了添加、删除、查找等操作,而 Vector
除了这些基本操作外,还提供了按索引访问元素、在指定位置插入元素等功能,进而就可以很好的支持排序算法,二分查找,堆算法等,它的缺点是扩容要付出一定的代价,而且除了尾上的插入和删除外其他位置的插入和删除都不快(因为要挪动数据)。
list 代码实现
#include <iostream>
#include <assert.h>
using namespace std;
namespace hd
{
template<class T>
struct ListNode
{
ListNode<T>* _next;
ListNode<T>* _prev;
T _data;
ListNode(const T& x = T()) // ListNode的构造函数
:_next(nullptr)
,_prev(nullptr)
,_data(x)
{
}
};
template<class T, class Ref, class Ptr>
struct _list_iterator // 链表迭代器
{
typedef ListNode<T> Node;
typedef _list_iterator<T, Ref, Ptr> self;
Node* _node; //存放一个节点的指针变量
_list_iterator(Node* node)
:_node(node)
{
}
//++it
self& operator++() {
_node = _node->_next;
return *this;
}
//it++
self operator++(int) {
self tmp(*this);
_node = _node->_next;
return tmp;
}
//--it
self& operator--() {
_node = _node->_prev;
return *this;
}
//it--
self operator--(int) {
self tmp(*this);
_node = _node->_prev;
return tmp;
}
// 模仿指针的 *
Ref operator*() {
return _node->_data;
}
// 模仿指针的 ->
Ptr operator->() {
return &_node->_data;
}
bool operator != (const self& s) {
return _node != s._node;
}
bool operator == (const self& s) {
return _node == s._node;
}
};
template<class T>
class list // 带头双向循环链表
{
typedef ListNode<T> Node; // 节点的重定义
public:
typedef _list_iterator<T, T&, T*> iterator; // 迭代器的重定义
typedef _list_iterator<T, const T&, const T*> const_iterator; // const迭代器的重定义
//迭代器相关
iterator begin() {
return _head->_next;
}
iterator end() {
return _head;
}
const_iterator begin() const {
return _head->_next;
}
const_iterator end() const {
return _head;
}
void empty_init() {
// 初始化链表
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
}
list() {
//构造函数
empty_init();
}
void clear() {
//清除链表元素
iterator it = begin();
while (it != end()) {
it = erase(it);
}
}
~list() {
//析构函数
clear();
delete _head;
_head = nullptr;
}
list(const list<T>& It) {
// 拷贝构造
empty_init();
for (const auto& e : It) {
push_back(e);
}
}
void swap(list<T> tmp) {
std::swap(_head, tmp