自己写过list 的人都知道, list 中的 节点在删除的时候 只会影响相邻的节点, 也并不会影响指向相邻节点的指针使用。
std标准模板库 引入的迭代器提供了对 容器元素统一 的访问 遍历 模型。其中很多迭代器都只能是临时持有, 做完访问使用后就得析构掉。即便持有也无法保证下次使用时访问的正确。但 list 却是个例外
list 的节点结构如下:
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer next;
void_pointer prev;
T data;
};
list的迭代器结构如下:
template<class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
typedef __list_iterator<T, Ref, Ptr> self;
typedef bidirectional_iterator_tag iterator_category;
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef __list_node<T>* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
link_type node;
__list_iterator(link_type x) : node(x) {}
__list_iterator() {}
__list_iterator(const iterator& x) : node(x.node) {}
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
reference operator*() const { return (*node).data; }
pointer operator->() const { return &(operator*()); }
self& operator++() {
node = (link_type)((*node).next);
return *this;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
self& operator--() {
node = (link_type)((*node).prev);
return *this;
}
self operator--(int) {
self tmp = *this;
--*this;
return tmp;
}
};
上面2个看上去和数据结构课里教的一样吧,而且list的删除操作也很标准:
iterator erase(iterator position) {
link_type next_node = link_type(position.node->next);
link_type prev_node = link_type(position.node->prev);
prev_node->next = next_node;
next_node->prev = prev_node;
destroy_node(position.node);
return iterator(next_node);
}
由此可见保留list::iterator的操作 是没问题的, 这样就能解决不少类似排队 系统的需求了, 如果排队的用户离开, 只要直接把他之前保存的iterator erase掉,而不需要再遍历一次了。
还有一个排队常见需求是 要求定时同步当前排队的顺序。 按说标准是支持当前 iterator - begin 这种写法来算 ptrdiff_t 的, 但list的迭代器却不行, 需要用到另外一个std的接口 distance(iter,begin) 来计算才行。