【问题标题】:Custom linked list const_iterator cannot traverse non-const instance of list自定义链表const_iterator不能遍历list的非常量实例
【发布时间】:2018-07-17 23:50:38
【问题描述】:

作为学习 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 的构造函数并将指针传递给(非常量)链表中的第一个节点时(当我调用@ 987654330@和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&lt;int&gt; *const 的函数式转换 到LList&lt;int&gt;::const_iterator(又名LList_iterator&lt;const int&gt;

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

【问题讨论】:

  • Node&lt;T&gt; 确实与Node&lt;const T&gt; 完全无关,并且是您错误的原因。大多数情况下,解决方案是硬着头皮为 const 情况重写整个迭代器类。
  • 或者,也许您可​​以有 1 个具有 2 个模板参数的迭代器类 - 1 个用于节点数据类型 (T),1 个用于迭代器的 value_typeTconst T ) 运营商采取行动。

标签: c++ iterator


【解决方案1】:

我认为你需要这样做:

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;

【讨论】:

  • 是的,我想编写另一个迭代器类将是要走的路。这对我有用!
猜你喜欢
  • 2011-09-24
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多