自己的迭代器不起作用

Own Iterator doesn't work

本文关键字:不起作用 迭代器 自己的      更新时间:2023-10-16

我处理自己的iterator,它应该迭代双链表。如果我在迭代,for循环会立即跳过。我没有错误,但从调试中我读得不多。

for周期:

for(SemestralWork::DoubleList<Student>::iterator it = link->begin(); it != link->end(); ++it){
//something...
}

iterator+begin()+end():

class iterator {
private:
Node<T> * node;
public:
iterator(){}
iterator(const iterator& cit){}
iterator(T t) {
}
~iterator(){}
iterator& operator=(const iterator& second){
node = second.node;
return(*this);
}
iterator& operator++(){     
if (node != NULL){
node = node->GetNext();
}
return(*this);
}
iterator operator++(int){
iterator tmp = *this;   //iterator tmp(*this)
operator++();
return tmp;
}
bool operator==(const iterator& second) {
return node == second.node;
}
bool operator!=(const iterator& second) {
return node != second.node;
}
T& operator*() {return node->GetData();}
T* operator->(){return((DoubleList<T>::iterator)*this);} 
};
iterator begin(){
return iterator(first->GetData());
}
iterator end(){
return iterator(last->GetData());
}

Node:

template <class U>
class Node{
Node<U> * next;
Node<U> * previous;
U data;
public:
Node(const U &data){
next = NULL;
previous = NULL;
this->data = data;
}
void SetNext(Node<U> *next) { this->next = next; }
Node<U> *GetNext(){ return next; }
void SetPrevious(Node<U> *previous) { this->previous = previous; }
Node<U> *GetPrevious(){ return previous; }
U &GetData() { return data; }
};

以下是我注意到的一些事情。这些是否真的能解决你的问题我不知道,因为发布的代码不完整:

  1. 您的iterator不应该从T对象构造,构造函数的实现实际上应该做一些事情(我猜iterator::iterator(T)根本不做任何事情是您的实际问题)。相反,iterator应该由Node<T>*构成
  2. 预注册操作符应该而不是检查是否真的有下一个元素!迭代器可以递增是operator++()的先决条件。如果发生任何情况,操作员应在启用调试设置的情况下报告误用
  3. 我对last的使用持怀疑态度:请注意,结束迭代器是最后一个元素后一个的位置
  4. 您的比较参与者应该是const成员,通常operator!=()只是代表operator==(),即:

    bool iterator::operator!=(iterator const& other) const {
    return !(*this == other);
    }
    

    这种实现方式的优点是,即使operator==()的实现方式改变,operator!=()也与operator==()一致。

您没有发布显示firstlast的列表实现,但我假设last指向最后一个元素。对于迭代器,end()应该将指向最后一个元素之外,而不是将指向最后一元素。例如,如果列表中正好包含1个元素,那么由于first == lastbegin() == end(),For循环根本不会运行。