自己的迭代器不起作用
Own Iterator doesn't work
我处理自己的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; }
};
以下是我注意到的一些事情。这些是否真的能解决你的问题我不知道,因为发布的代码不完整:
- 您的
iterator
不应该从T
对象构造,构造函数的实现实际上应该做一些事情(我猜iterator::iterator(T)
根本不做任何事情是您的实际问题)。相反,iterator
应该由Node<T>*
构成 - 预注册操作符应该而不是检查是否真的有下一个元素!迭代器可以递增是
operator++()
的先决条件。如果发生任何情况,操作员应在启用调试设置的情况下报告误用 - 我对
last
的使用持怀疑态度:请注意,结束迭代器是最后一个元素后一个的位置 -
您的比较参与者应该是
const
成员,通常operator!=()
只是代表operator==()
,即:bool iterator::operator!=(iterator const& other) const { return !(*this == other); }
这种实现方式的优点是,即使
operator==()
的实现方式改变,operator!=()
也与operator==()
一致。
您没有发布显示first
和last
的列表实现,但我假设last
指向最后一个元素。对于迭代器,end()
应该将指向最后一个元素之外,而不是将指向最后一元素。例如,如果列表中正好包含1个元素,那么由于first == last
和begin() == end()
,For循环根本不会运行。
相关文章:
- 为什么output_editor Concept不需要output_e迭代器标记
- C++不兼容的迭代器类型
- 使用 find() 通过 std::set 的迭代器将不起作用。出了什么问题?
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- 我可以在 std::list 中移动元素而不会使迭代器或引用无效,但是如何移动呢?
- 为什么我不能将迭代器应用于接受 const_iterator 引用的函数?
- 与运算符"!="不匹配(c++ 迭代器)
- 如何不擦除迭代器(从"Effective STL")
- 有人能解释一下他们的意思是list.pushback文档(不会使迭代器无效)吗
- 不会使迭代器(和指针)无效的容器
- std::cin >>向量[i]不会让迭代器正常工作吗?
- 调试断言错误 - 列出不兼容的迭代器
- c++:不能给迭代器赋索引
- 我可以(a)不通过输入迭代器写入,或者(b)只通过一个迭代器读取一次吗?
- c++不需要删除迭代器
- C++列出不兼容的迭代器
- std::for_each等效项,它不取消引用迭代器
- 不带循环迭代器的枚举
- std::list擦除不兼容的迭代器
- 深度缓冲区似乎不起作用-OpenGL着色器