自定义链表const_iterator无法遍历列表的非const实例

Custom linked list const_iterator cannot traverse non-const instance of list

本文关键字:const 列表 遍历 实例 链表 iterator 自定义      更新时间:2023-10-16

作为学习C++的练习,我正在尝试为链表编写一个自定义迭代器。

使用以下struct:添加列表中的节点

template <class T> struct Node {
T val;
Node* next;
Node* prev;
Node(const T& new_val): val(new_val), next(0), prev(0) { }
};

下面是迭代器的相关部分:

template <class T> class LList_iterator {
public:
//...
LList_iterator(Node<T>* p): node(p) { }
//...
private:
Node<T>* node;
};

链表为iteratorconst_iterator:提供typedef

template <class T> class LList {
public:
typedef LList_iterator<T> iterator;
typedef LList_iterator<const T> const_iterator;
iterator begin() { return iterator(head); }
const_iterator cbegin() const { return const_iterator(head); }
iterator end() { return iterator(0); }
const_iterator cend() const { return const_iterator(0); }
//...
private:
Node<T>* head;
};

我可以正确使用iterator,但每当我调用const_iterator的构造函数并将指针传递到(非常数(链表中的第一个节点时(当我调用cbegin()cend()时(,编译器就会抛出错误:

LList<int> l;
l.push_back(10);
for (LList<int>::const_iterator i = l.cbegin(); i != l.cend(); ++i)
std::cout << *i << std::endl;

错误:Node<int> *const没有匹配的函数样式转换至LList<int>::const_iterator(又名LList_iterator<const int>(

我认为这可能是因为const_iterator(const int(所期望的Node类型与我正在遍历的列表中的类型(类型为int(不同。如果是这种情况,我有没有办法"临时"将LList模板参数转换为const int?还是我对错误的理解被误导了?

我认为您需要这样做:

template <class T> class LList_const_iterator {
public:
//...
LList_iterator(const Node<T>* p): node(p) { }
//...
private:
const Node<T>* node;
};

并更改你的typedef

// from
typedef LList_iterator<const T> const_iterator;
// to
typedef LList_const_iterator<T> const_iterator;