在C++中list底层是由双向队列实现的,其中它的迭代器为了实现出和vector容器的迭代器一样的使用效果(vector的空间是连续的,而list的空间是不连续的),因此对list的迭代器进行自定义了一些方法,其中如指针的解引用,迭代器的类中必须重载operator*()、指针的++自定义的是operator++() 返回一个指向下一个节点的指针等等这些对指针的函数重载,实现了和vector容器的迭代器一样的使用方法,list具体实现如下所示:
#pragma once
#include<assert.h>
#include<iostream>
using namespace std;
namespace sdk
{
template<class T>
struct _list_node
{
T _val;
_list_node<T>* _prev;
_list_node<T>* _next;
_list_node(const T &val=T()):_val(val),_prev(nullptr),_next(nullptr)
{
}
};
//template<class T>
template<class T, class Ref, class Ptr>
struct _list_iterator
{
typedef _list_node<T> node;
typedef _list_iterator<T, Ref, Ptr> self;
node* _pnode;
_list_iterator(node* pnode):_pnode(pnode)
{}
Ref& operator*()
{
return _pnode->_val;
}
bool operator!=( const self& s)const
{
return _pnode != s._pnode;
}
self& operator++()
{
_pnode = _pnode->_next;
return *this;
}
};
template<class T>
class List
{
typedef _list_node<T> node;
public:
typedef _list_iterator<T, T&, T*> iterator;
typedef _list_iterator<T, const T&, const T*> const_iterator;
iterator begin()
{
return iterator(_head->_next);
}
const_iterator begin() const
{
return const_iterator(_head->_next);
}
iterator end()
{
return iterator(_head);
}
const_iterator end() const
{
return const_iterator(_head);
}
List()
{
_head = new node;
_head->_next = _head;
_head->_prev = _head;
}
List(const List<T>& lt)
{
_head = new node;
_head->_next = _head;
_head->_prev = _head;
for (auto &e : lt)
{
push_back(e);
}
}
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;
}
List<T>& operator=(List<T> lt)
{
swap(_head, lt._head);
return *this;
}
void insert(iterator pos, const T&x)
{
assert(pos._pnode);
node* cur = pos._pnode;
node* prev = cur->_prev;
node* newnode = new node(x);
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
}
iterator erase(iterator pos)
{
assert(pos._pnode);
assert(pos != end());
node* cur = pos._pnode;
node* prev = cur->_prev;
node* next = cur->_next;
prev->_next = next;
next->_prev = prev;
delete pos._pnode;
return iterator(next);
}
~List()
{
clear();
delete _head;
_head = nullptr;
}
void clear()
{
iterator it = _head->_next;
while (it != _head)
{
it = erase(it);
}
}
private:
node* _head;
};
void PrintList(const List<int>& lt)
{
List<int>::const_iterator it = lt.begin();
while (it != lt.end())
{
//*it += 1; // ?
cout << *it << " ";
++it;
}
cout << endl;
}
void Test1()
{
sdk:: List<int> l1;
l1.push_back(5);
l1.push_back(4);
l1.push_back(3);
l1.push_back(2);
l1.push_back(1);
List<int>::iterator it = l1.begin();
//++it;
++it;
//l1.insert(it, -1);
sdk::List<int> l2;
l2.push_back(-1);
l2.push_back(-2);
l2.push_back(-3);
l1.erase(it);
List<int>copy(l1);
PrintList(l1);
PrintList(copy);
copy = l2;
PrintList(copy);
}
}