自定义链表const_iterator无法遍历列表的非const实例
Custom linked list const_iterator cannot traverse non-const instance of list
作为学习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;
};
链表为iterator
和const_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;
相关文章:
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 自定义链表const_iterator无法遍历列表的非const实例
- 在形式参数列表中自动使用 const 和按引用传递的任何明显后果
- 变量参数列表 后面的'const std::string&'弄乱了堆栈
- 如何将 const 应用于 C++ 中参数列表之外的模板参数类型?
- 将整数值分配为variadic模板列表到静态const std ::数组成员
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- 如何将指向指针列表的私有指针作为 const 返回
- QT-如何从const函数附加到本地列表
- 在没有初始化列表的情况下,在c++的headerfile中为const int赋值
- 使用 const 和 打印列表
- C/C++:函数参数列表中的"const"位置
- 将类型转换应用于列表:"const"特别吗?
- 如何在成员初始化列表中为const char*类成员分配内存
- 如何创建一个带有const内容的c#列表
- C++:以"const pointer"为成员的列表与以"pointer to const"为成员的列表
- 用初始化列表初始化包含const数组的Struct
- 指向Const数据和c++列表的Const指针
- c++编译器将列表转换为const列表
- 定义const列表