// Created by Igor Markov, Feb 17, 2001 // This program demonstrates the difference between a stack and a queue // and also how to use them interchangeably // (this is one of half a dozen possible approaches to Project 1) #include #include #include typedef int MyWeirdClass; // can be something else in your application class STLContainerWrapper { stack _st; queue _qu; public: enum Mode { BehaveLikeAStack, BehaveLikeAQueue }; private: Mode _mode; public: STLContainerWrapper(Mode mode) :_mode(mode) {} bool isEmpty() { return ( _mode== BehaveLikeAStack ? _st.empty() : _qu.empty()) ; } MyWeirdClass removeElement() { MyWeirdClass tmp; if (_mode== BehaveLikeAStack){ tmp=_st.top(); _st.pop(); } else { tmp=_qu.front(); _qu.pop(); } return tmp; } void addElement(MyWeirdClass elt) { if (_mode== BehaveLikeAStack) _st.push(elt); else _qu.push(elt); } }; int main() { STLContainerWrapper w1(STLContainerWrapper::BehaveLikeAStack); cout << " Let's run in the stack mode first : adding 5, 6, 7 ..." << endl; w1.addElement(5); w1.addElement(6); w1.addElement(7); cout << " Remove those elements and see what the order is :" << endl; cout << w1.removeElement() << ", "; cout << w1.removeElement() << ", "; cout << w1.removeElement() << endl; STLContainerWrapper w2(STLContainerWrapper::BehaveLikeAQueue); cout << " Now run in the queue mode : adding 5, 6, 7 ..." << endl; w2.addElement(5); w2.addElement(6); w2.addElement(7); cout << " Remove those elements and see what the order is :" << endl; cout << w2.removeElement() << ", "; cout << w2.removeElement() << ", "; cout << w2.removeElement() << endl; }