0
// 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)。有一个错误:“预期';' 前 '!' 令牌”。那是怎么回事?

4

4 回答 4

11

你有一个错字operator!=

p!rhs.p

应该读

p != rhs.p

或者,更一般地说,

!(*this == rhs)

此行中还有一个无效的空字符常量:

std::cout << *it << '';
                    ^^  // Get rid of that, or change it to something sensible
于 2013-10-31T15:15:51.973 回答
7

看起来是这一行:

bool operator!=(const MyIterator& rhs){return p!rhs.p;}

将其更改为:

bool operator!=(const MyIterator& rhs){return p != rhs.p;}
于 2013-10-31T15:16:05.730 回答
3

我建议将 != 定义为

bool operator==(const MyIterator& rhs){return p == rhs.p;}
bool operator!=(const MyIterator& rhs){return !(*this == rhs);}

因此,如果 == 变得更复杂,您不必在 != 中复制代码

同样,您可以仅根据 < 和 == 来定义 < > <= >=,从而最大限度地减少代码重复

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);}
于 2013-10-31T15:23:05.140 回答
2

我相信这对!=操作员来说是超载的。该行应该是:

bool operator!=(const MyIterator& rhs){return p!=rhs.p;}
于 2013-10-31T15:17:56.643 回答