1 #include <iostream> 2 #include <stack> 3 4 template<typename Stack> 5 class stack_iterator 6 { 7 public: 8 typedef typename Stack::value_type value_type; 9 typedef typename Stack::reference reference; 10 private: 11 Stack &s; 12 value_type *pos; 13 public: 14 stack_iterator(Stack &_s):s(_s),pos(_s.size()?&_s.top():0){} 15 reference operator * () const {return *pos;} 16 stack_iterator& operator ++() 17 { 18 s.pop(); 19 pos = s.size()?&s.top():0; 20 return *this; 21 } 22 bool operator == (stack_iterator const &rh) const {return pos == rh.pos;} 23 bool operator != (stack_iterator const &rh) const {return pos !=r rh.pos;} 24 25 26 }; 27 28 int main() 29 { 30 using namespace std; 31 int num[]= {0,1,2,3,4}; 32 typedef stack<int> int_stack; 33 int_stack s; 34 for(int i = 0 ; i < 5 ;++ i ) 35 { 36 s.push(num[i]); 37 } 38 stack_iterator<int_stack> a(s); 39 stack_iterator<int_stack> b(s); 40 41 cout<<((a==b)?"a==b":"a!=b")<<endl; 42 ++a; 43 ++b; 44 cout<<((a==b)?"++a==+=b":"++a!=++b")<<endl; 45 ++b; 46 ++b; 47 ++b; 48 cout<<*a<<endl; 49 cout<<*b<<endl; 50 getchar(); 51 }
这个迭代器是的预想是要在迭代器a和b同时指向一个栈,然后操作b,看a的指向是否有什么变化,理论上说b空,a也应该空,或者直接溢出,但是结果却是3,即指向没变。为什么呢