簡體   English   中英

自定義鏈接列表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;
};

鏈表為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和在(非const)指針傳遞給第一個節點鏈表(當我打電話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> *constLList<int>::const_iterator功能樣式匹配(又名LList_iterator<const int>

我相信這可能是因為const_iteratorconst 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM