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 に答える