2013-10-31 46 views
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)。 有一個錯誤:「預計」;「在'!'之前令牌」。 這是怎麼回事?錯誤:預期';'在'!'之前代幣

+0

請提供整個堆棧跟蹤 – Pol0nium

+0

哪一行產生編譯器錯誤? –

+3

回答此問題的人都戴着太陽鏡!大聲笑 – streppel

回答

11

你有operator!=一個錯字:

p!rhs.p 

應該讀

p != rhs.p 

,或者更一般地,

!(*this == rhs) 

你也有一個無效的空字符在該行不斷:

std::cout << *it << ''; 
        ^^ // Get rid of that, or change it to something sensible 
7

看起來像它的這一行:

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

它改成這樣:

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

我相信這是在過載爲!=操作。該行應該是:

bool operator!=(const MyIterator& rhs){return p!=rhs.p;} 
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);} 
+0

你甚至可以用'<和'=='而不是'<' and '> ='來定義'<' '>'<=' and '> ='。 – Yakk

+0

@Yakk所以你可以!更新,謝謝 –

相關問題