您的位置:首页 > 产品设计 > UI/UE

Queue and Stack

2015-03-15 15:32 441 查看
Basic operations for queue and stack.

#include<iostream>
#include<list>
#include<vector>
#include<string>
#include<stack>
#include<queue>

using namespace std;

template <class T, class Container>
void printStack(stack<T, Container> s){
while(!s.empty()){
cout << s.top() << endl;
s.pop();
}
}

template <class T, class Container>
void printQueue(queue<T, Container> s){
while(!s.empty()){
cout << s.front() << endl;
s.pop();
}
}

int main(){
stack<int, vector<int> > s;
for(int i=0; i<4; i++){
s.push(i+1);
}
printStack(s);

string str = "a";
queue<string, deque<string> > t;
for(int i=0; i<4; i++){
t.push(str);
str += 'a';
}
printQueue(t);

return 0;
}

We could also extend basic stack class, for instance, create a stack class with limitation of its size.
#include<iostream>
#include<list>
#include<vector>
#include<string>
#include<stack>
#include<queue>

using namespace std;

template<class T, class Container=deque<T> >
class mystack : public stack<T, Container>{
private:
int MaxSize;
public:
mystack():MaxSize(0){}
mystack(int MaxSize_):MaxSize(MaxSize_){}

void push(const T& t){
if(int(stack<T, Container>::size())<MaxSize){
stack<T, Container>::push(t);
}else{
cout << "stack is fill, cannot add items!" << endl;
}
}
};

int main(){
mystack<int, deque<int> > s(2);
cout << s.size() << endl;
s.push(1);
s.push(2);
s.push(3);

return 0;
}Here, we call the function in base class via
stack<T, Container>::push(t)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: