C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
上篇文章:
https://blog.csdn.net/2401_86123468/article/details/154244503?spm=1001.2014.3001.5501
C++文档:
https://legacy.cplusplus.com/reference/
本文代码和list源码:
https://gitee.com/jxxx404/cpp-language-learning/tree/master/list
我数据结构的专栏为近期文章基础:
https://blog.csdn.net/2401_86123468/category_13017825.html
1.阅读list源码
1.1结点结构分析
通过定义的结点可以看出,list就是一个双向链表

链表的结构

1.2链表核心成员变量

转到link_type定义,发现node是一个结点的指针

根据以上观察,我们可以大致的猜测node可能是指向头结点之类的,那么究竟是什么结构?需要我们了解其核心的初始化和核心的成员函数。
1.3核心构造初始化
这里表现为空初始化

转到空初始化的定义,可以看出此处为哨兵位的头结点

注意:这里的get_node()不需要new,是因为会调用内存池申请结点
见下

总结上述代码,get_node()为获取一个结点,put_node()是释放结点,create_node为初始化,其中的construct是调定位new,不过我们模拟实现只需要new/delete即可。
destroy()对应的析构,此处析构的意义举例:在list中定义了string,如:list<string>lt,那么在析构时不能只调用其自己的结点,也需要对string析构。并且在C++中,可以认为内置类型也有构造和析构,因为这里的T可以是基本类型也可以是类类型等。
见下图:

1.4核心操作实现
此处的push_back等涉及到迭代器,因此我们先通过现有的知识开始模拟实现list类,实现结束后再来了解此处知识。

2.list类模拟实现
2.1创建结点结构体
首先我们需要创建一个结点的结构,一个类如果所有成员不希望通过访问限定符限定时,就定义为struct。
template<class T>
struct list_node
{list_node<T>* _next;list_node<T>* _prev;T _data;list_node(const T& x = T()):_next(nullptr),_prev(nullptr),_data(x){ }
};
此处list_node结构体是公有的,但由于list类的_head成员是私有的,外部代码无法直接操作链表的内在连接结构。所有对链表的操作都必须通过list类提供的公共接口(如迭代器、push_back等)来完成,这实际上提供了足够的封装保护。
2.2循环列表初始化
template<class T>
class list
{using Node = list_node<T>;
public:list(){_head = new Node;_head->_next = _head;_head->_prev = _head;}
private:Node* _head;
};
2.3push_back

void push_back(const T& x)
{Node* newnode = new Node(x);Node* tail = _head->_prev;tail->_next = newnode;newnode->_prev = tail;newnode->_next = _head;_head->_prev = newnode;
}
2.4迭代器的实现
迭代器的设计是一种封装,封装隐藏底层的结构差异,提供类似的统一方式访问容器。
最基本的结构:
template<class T>
struct list_iterator
{using Self = list_iterator<T>;using Node = list_node<T>;Node* _node;list_iterator(Node* node):_node(node){ }//*itT& operator*(){return _node->_data;}//++itSelf& operator++(){_node = _node->_next;return *this;}Self operator++(int){Self temp(*this);_node = _node->_next;return temp;}Self& operator--(){_node = _node->_prev;return *this;}Self operator--(int){Self temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& s) const{return _node != s._node;}bool operator==(const Self& s) const{return _node == s._node;}
};
迭代器支持类:
using iterator = list_iterator<T>;iterator begin()
{return iterator(_head->_next);
}iterator end()
{return iterator(_head);
}
2.5insert

void insert(iterator pos, const T& x)
{Node* cur = pos._node;Node* prev = cur->_prev;Node* newnode = new Node(x);//prev newnode curprev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;
}
2.6erase
不过此时有迭代器失效的风险
void erase(iterator pos)
{Node* cur = pos._node;Node* prev = cur->_prev;Node* next = cur->_next;prev->_next = next;next->_prev = prev;delete cur;
}
2.7复用insert完成前插尾插
void push_back(const T& x)
{insert(end(), x);
}void push_front(const T& x)
{insert(begin(), x);
}
2.8复用erase完成尾删头删
void pop_front()
{erase(begin());
}void pop_back()
{erase(--end());
}
测试代码:
xxx::list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);
lt.push_front(-2);
lt.push_front(-5);for (auto e : lt)
{cout << e << " ";
}
cout << endl;lt.pop_back();
lt.pop_back();
lt.pop_front();
lt.pop_front();for (auto e : lt)
{cout << e << " ";
}
cout << endl;
2.9size
size_t size() {size_t n = 0;/*for (auto& e : *this){++n;}return n;*/return _size;}private:Node* _head;size_t _size = 0;
};
2.10析构,优化erase
~list()
{iterator it = begin();while (it != end()){it = erase(it);}
}
注意:上述代码erase之后会失效,但是其会有一个返回值,返回删除数据的下一个位置:

因此,优化erase
iterator erase(iterator pos)
{Node* cur = pos._node;Node* prev = cur->_prev;Node* next = cur->_next;prev->_next = next;next->_prev = prev;delete cur;--_size;//return iterator(next);return next;//两种写法,可以隐式类型转换
}
2.11clear,优化析构
void clear()
{iterator it = begin();while (it != end()){it = erase(it);}
}
~list()
{clear();delete _head;_head = nullptr;_size = 0;
}
3.构造
3.1修改2.2中的默认构造函数
void empty_init()
{_head = new Node;_head->_next = _head;_head->_prev = _head;
}list()
{empty_init();
}
上述代码实现了链表中基础的初始化,解决了首次插入时,pos为空的问题。
3.2初始化列表构造函数
list(initializer_list<T> il)
{empty_init();for (auto& e : il){push_back(e);}
}
3.3迭代器区间的构造
template <class InputIterator>list(InputIterator first, InputIterator last){empty_init();while(first != last){push_back(*first);++first;}}
3.4n个val的构造
list(size_t n, T val = T())
{empty_init();for (size_t i = 0; i < n; ++i){push_back(val);}
}
list(int n, T val = T())
{empty_init();for (int i = 0; i < n; ++i){push_back(val);}
}
3.5交换
void swap(list<T>& lt)
{std::swap(_head, lt._head);std::swap(_size, lt._size);
}
3.5拷贝构造
由于还没有创建const迭代器,所以此时拷贝构造其实不能算完成,到文章4.1部分结束即可正确调用,不过先在这里展示正确写法:
//传统写法
//lt2(lt1)
list(const list<T>& lt)
{empty_init();for (auto e : lt){push_back(e);}
}
//lt1 = lt3
list<T>& operator=(const list<T>& lt)
{if (this != <){clear();for (auto& e : lt){push_back(e);}}return *this;
}
//现代写法
//lt2(lt1)
list(const list<T>& lt)
{empty_init();list<T> tmp(lt.begin(), lt.end());swap(tmp);
}
//lt1 = lt3
list<T>& operator=(list<T>& tmp)
{swap(tmp);return *this;
}
4.const迭代器
测试代码:
void Print(const xxx::list<int>& lt)
{xxx::list<int>::const_iterator it = lt.begin();while (it != lt.end()){cout << *it << " ";++it;}cout << endl;
}
const迭代器与普通迭代器的区别在于返回的别名不同,因此原始的方法就是将上述完成的迭代器拷贝一份并且改变解引用的返回类型:
//const
template<class T>
struct list_const_iterator
{using Self = list_const_iterator<T>;using Node = list_node<T>;Node* _node;list_const_iterator(Node* node):_node(node){}//*itconst T& operator*(){return _node->_data;}//++itSelf& operator++(){_node = _node->_next;return *this;}Self operator++(int){Self temp(*this);_node = _node->_next;return temp;}Self& operator--(){_node = _node->_prev;return *this;}Self operator--(int){Self temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& s) const{return _node != s._node;}bool operator==(const Self& s) const{return _node == s._node;}
};
对迭代器begin和end也加const:
const_iterator begin() const
{return const_iterator(_head->_next);
}const_iterator end() const
{return const_iterator(_head);
}
4.1优化const迭代器
之前的代码,我们都将部分返回类型写为Self,那么此时我们再多增加一个类Ref,并定义const迭代器返回const Ref&,将解引用的返回类型也改为Ref:
template<class T, class Ref>
struct list_iterator
{using Self = list_iterator<T, Ref>;using Node = list_node<T>;Node* _node;list_iterator(Node* node):_node(node){ }//*itRef operator*(){return _node->_data;}//++itSelf& operator++(){_node = _node->_next;return *this;}Self operator++(int){Self temp(*this);_node = _node->_next;return temp;}Self& operator--(){_node = _node->_prev;return *this;}Self operator--(int){Self temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& s) const{return _node != s._node;}bool operator==(const Self& s) const{return _node == s._node;}
};
template<class T>
class list
{using Node = list_node<T>;
public:using iterator = list_iterator<T, T&>;using const_iterator = list_iterator<T, const T&>;
//其余不变
对比区别:


5.对于非常规类型的处理,再优化迭代器模板
struct AA
{int _a1;int _a2;AA(int a1 =0, int a2 = 0):_a1(a1),_a2(a2){ }
};void test_list4()
{xxx::list<AA> lt;lt.push_back({ 1,1 });lt.push_back({ 2,2 });lt.push_back({ 3,3 });xxx::list<AA>::iterator it = lt.begin();while (it != lt.end()){//cout << (*it)._a1 << ":" << (*it)._a2 << endl;//不同的表现形式:cout << it->_a1 << ":" << it->_a2 << endl;++it;}cout << endl;
}
上述代码->的底层理解为:
cout << it->_a1 << ":" << it->_a2 << endl;
//底层见下:
cout << it.operator->()->_a1 << ":" << it.operator->()->_a2 << endl;
在头文件中多添加一个重载箭头运算符:
//*it
Ref operator*()
{return _node->_data;
}T* operator->()
{return &_node->_data;
}
不过此时依旧要考虑const,所以再次优化模板为:
迭代器模板类:

list类定义:

本章完。
