// std:: iterator sample
#include <iostream> // std::cout
#include <iterator> // std::iterator, std::input_iterator_tag
class MyIterator:public std::iterator<std::input_iterator_tag, int>
{
int *p;
public:
MyIterator(int *x):p(x){}
MyIterator(const MyIterator& mit):p(mit.p){}
MyIterator& operator++(){++p; return *this;}
MyIterator operator++(int){MyIterator tmp(*this);operator++(); return tmp;}
bool operator==(const MyIterator& rhs){return p == rhs.p;}
bool operator!=(const MyIterator& rhs){return p!rhs.p;}
int& operator*(){return *p;}
};
int main(){
int numbers[] = {10, 20, 30, 40, 50};
MyIterator from(numbers);
MyIterator until(numbers+5);
for (MyIterator it=from; it!=until; it++)
std::cout << *it << '';
std::cout << '\n';
return 0;
};
当我试图更好地理解“迭代器”是什么时。我将这些代码复制到我的编译器(codeBlock)。 有一个错误:“预期';'在'!'之前令牌”。 这有什么关系?
答案 0 :(得分:11)
operator!=
中有拼写错误:
p!rhs.p
应该阅读
p != rhs.p
或者,更一般地说,
!(*this == rhs)
此行中还有一个无效的空字符常量:
std::cout << *it << '';
^^ // Get rid of that, or change it to something sensible
答案 1 :(得分:7)
看起来就是这一行:
bool operator!=(const MyIterator& rhs){return p!rhs.p;}
将其更改为:
bool operator!=(const MyIterator& rhs){return p != rhs.p;}
答案 2 :(得分:3)
我建议定义!= as
bool operator==(const MyIterator& rhs){return p == rhs.p;}
bool operator!=(const MyIterator& rhs){return !(*this == rhs);}
因此,如果==变得更复杂,您不必在!=
中复制代码同样,您可以定义&lt; &GT; &lt; =&gt; =仅仅&lt;和==,尽量减少代码重复
bool operator == (const MyIterator& rhs) const {return p == rhs.p;}
bool operator < (const MyIterator& rhs) const {return p < rhs.p;}
bool operator <= (const MyIterator& rhs) const {return (*this == rhs) || (*this < rhs);}
bool operator != (const MyIterator& rhs) const {return !(*this == rhs);}
bool operator >= (const MyIterator& rhs) const {return !(*this < rhs);}
bool operator > (const MyIterator& rhs) const {return !(*this <= rhs);}
答案 3 :(得分:2)
我相信!=
运营商的过载。该行应该是:
bool operator!=(const MyIterator& rhs){return p!=rhs.p;}