首页 新闻 会员 周边 捐助

栈的 迭代器问题

0
悬赏园豆:50 [待解决问题]

 

 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,即指向没变。为什么呢

struggle_time的主页 struggle_time | 初学一级 | 园豆:152
提问于:2014-11-18 11:03
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册