Skip to content

Commit 815debd

Browse files
authored
list迭代器模拟实现
1 parent 8fe9b65 commit 815debd

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

list_iterator

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//list迭代器的实现
2+
//Ref->T& ptr->T*
3+
template<class T, class Ref, class Ptr>
4+
struct __list_iterator
5+
{
6+
typedef __list_node<T> node;
7+
typedef __list_iterator<T, Ref, Ptr> self;
8+
node* _node;
9+
10+
//迭代器的作用不是创建节点而是指向原有节点,因此使用指针即可
11+
__list_iterator(node* node)
12+
:_node(node)
13+
{}
14+
//list迭代器中不用实现拷贝构造、赋值运算符重载、析构,因为迭代器的本质并不是创建节点,使用默认的进行值拷贝即可。
15+
bool operator!=(const self& s) const //不需要进行修改,设计成const无论是const和非const都可以调用
16+
{
17+
return _node != s._node;
18+
}
19+
bool operator==(const self& s) const
20+
{
21+
return _node == s._node;
22+
}
23+
//重载->
24+
Ptr operator->() const
25+
{
26+
return &_node->data;
27+
}
28+
Ref operator*() const
29+
{
30+
return _node->data;
31+
}
32+
//前置++
33+
self operator++()
34+
{
35+
_node = _node->next;//直接返回++后的结果
36+
return *this;
37+
}
38+
//后置++
39+
self operator++(int) //参数只是为了和前置构成重载,并没有实际意义,因此只给类型就可以了
40+
{
41+
self tmp = *this;
42+
_node = _node->next;
43+
return tmp;
44+
}
45+
//前置--
46+
self operator--()
47+
{
48+
_node = _node->next;
49+
return *this;
50+
}
51+
//后置--
52+
self operator--(int)
53+
{
54+
self tmp = *this;
55+
_node = _node->next;
56+
return tmp;
57+
}
58+
};

0 commit comments

Comments
 (0)