Определите стек, похожий на тип stack (параграф 17.3.1), но который не копирует нижележащий контейнер (на котором он базируется) и который допускает итерацию по своим элементам.
Тоже простенькая задачка, правда я чуток сразу запутался с ней. Просто создаем простую версию стека. Я не буду описывать как что делать, я думаю и так все ясно. В общем от код и все.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
#include <iostream> using std::cout; using std::endl; #include <cstdlib> using std::exit; class Stack { int* data; int count; public: struct iterator { int* k; void operator=(int* a){k=a;} int operator*(){return *k;} void operator++(){k++;} void operator++(int){k++;} bool operator!=(int* a){return k!=a;} }; Stack():count(0){} void push(int n) { if(count==0)//pervui element { data=new int[++count]; data[count-1]=n; } else//count>=1 { //cout <<"count= "<<count<<endl; int* data1=new int[++count]; for(int i=0;i<count;++i) { if(i!=count-1) data1[i]=data[i]; else data1[i]=n; } //сохраняем указатель на область памяти для удаления int* temp=data; data=data1; //освобождаем память delete [] temp; } } void pop() { if(count!=0) count--; } int& top() { //cout <<"count= "<<count<<endl; if(count!=0) return data[count-1]; else { cout <<"Stack is empty "; int k=0; return k; } } int* begin() { return data; } int* end() { return data+count; } }; int main() { Stack s; s.push(1); s.push(2); s.push(3); cout <<s.top()<<endl; s.pop(); cout <<s.top()<<endl; s.pop(); cout <<s.top()<<endl; s.pop(); cout <<s.top()<<endl<<endl; s.push(1); s.push(2); s.push(3); //создаем итератор Stack::iterator it; it=s.begin(); for(it=s.begin();it!=s.end();++it) cout <<*it<<' '; cout <<endl; return 0; } |
[youtube]http://www.youtube.com/watch?v=-_dcvMuK9uU[/youtube]