namespace ljh {
template<class T>
struct ListNode {
ListNode<T>* _next;
ListNode<T>* _prev;
T _data;
ListNode(const T& data = T()) :_next(nullptr), _prev(nullptr), _data(data) {}
};
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* x) :_node(x){}
//it2(it1) 浅拷贝即可,默认的即可
Ref operator*() {
return _node->_data;
}
T* operator->() {
return &_node->_data;
}
self& operator++() {
_node = _node->_next;
return *this;
}
self& operator--() {
_node = _node->_prev;
return *this;
}
self operator++(int) {
__list_iterator<T> tmp(*this);
_node = _node->_next;
return tmp;
}
self operator--(int) {
__list_iterator<T> tmp(*this);
_node = _node->_prev;
return tmp;
}
bool operator!=(const self& it) const {
return _node != it._node;
}
bool operator==(const self& it) const {
return _node == it._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;
void f() {
Node* pnode = _head->_next;
iterator it = _head->_next;
*pnode;
*it;
++pnode;
++it;
}
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;
}
void push_back(const T& x) {
Node* tail = _head->_prev;
Node* newnode = new Node(x);
tail->_next = newnode;
newnode->_prev = tail;
newnode->_next = _head;
_head->_prev = newnode;
}
private:
Node* _head;
};
void print_list(const list<int>& lt) {
list<int>::const_iterator it = lt.begin();
while (it != lt.end()) {
std::cout << *it << " ";
++it;
}
std::cout << std::endl;
}
void test_list1() {
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.f();
list<int>::iterator it = lt.begin();
while (it != lt.end()) {
std::cout << *it << " ";
++it;
}
std::cout << std::endl;
}
struct Date {
int _year;
int _month;
int _day;
Date(int year=1, int month=1, int day=1) :_year(year), _month(month), _day(day) {}
};
void test_list2() {
list<Date> lt;
lt.push_back(Date(2022, 3, 12));
lt.push_back(Date(2022, 3, 13));
lt.push_back(Date(2022, 3, 14));
list<Date>::iterator it = lt.begin();
while (it != lt.end()) {
std::cout << it->_year<<"/"<<it->_month<<"/"<<it->_day<<std::endl;
//本来应该是it->->_year,但是因为可读性太差了,编译器进行了相关的优化
//所有类型,只要想重载->,都是这样的,都会省略一个->
++it;
}
std::cout<<std::endl;
}
}
C++stl 中 list的模拟实现
最新推荐文章于 2024-05-13 09:55:25 发布