链表常量迭代器

Linked list const iterator

本文关键字:迭代器 常量 链表      更新时间:2023-10-16

我实现了一个双向链表,并创建了一个扩展std::iterator的迭代器。我现在正在尝试创建一个const版本。

我试过了:

typename typedef list_iterator<T_>        iterator;
typename typedef list_iterator<T_> const  const_iterator;

但是,如果我这样做,则会出现此错误:

error C2678: binary '--' : no operator found which takes a left-hand operand of type 'const    list_iterator<T_>' (or there is no acceptable conversion)

这是我operator--

list_iterator& operator -- ()
{
    _current = _current->_previous;
    return *this;
}
list_iterator operator--(int) // postfix
{
    list_iterator hold = *this;
    --*this;
    return list_iterator( hold );
}

如果我把

list_iterator operator--() const

。我无法修改_current的值

我如何让我的迭代器现在像const_iterator一样工作,以便我可以从我的链表中调用 获取 begin()end() 的 const 版本,以及 cbegin()cend()

对。 问题是你对const_iterator类型def的声明。 (请参阅如何正确实现自定义迭代器和const_iterators?

而不是

typename typedef list_iterator<T_> const  const_iterator;

你想要

typename typedef list_iterator<const  T_> const_iterator;