Stack.h
- #ifndef STACK_H
- #define STACK_H
- #include <string>
- #include <vector>
- using namespace std;
- class Stack
- {
- public:
- Stack(string* lhs,string* rhs);
- bool push(const string& elem);
- bool pop(string& elem);
- bool peek(string& elem);
- bool full()const;
- int size();
- bool empty()const;
- void print()const;
- string& operator[](int index)
- {
- return _stack[index];
- }
- private:
- vector<string> _stack;
- };
- #endif
Stack.cpp
- #include <iostream>
- #include "Stack.h"
- Stack::Stack(string* lhs,string* rhs)
- {
- while(lhs != rhs)
- {
- _stack.push_back(*lhs);
- ++lhs;
- }
- }
- bool Stack::empty() const
- {
- return _stack.empty();
- }
- bool Stack::full()const
- {
- return _stack.size() == _stack.max_size();
- }
- bool Stack::peek(string& elem)
- {
- if (empty())
- {
- return false;
- }
- elem = _stack.back();
- return true;
- }
- bool Stack::push(const string& elem)
- {
- if (full())
- {
- return false;
- }
- _stack.push_back(elem);
- return true;
- }
- bool Stack::pop(string &elem)
- {
- if (empty())
- {
- return false;
- }
- elem = _stack.back();
- _stack.pop_back();
- return true;
- }
- int Stack::size()
- {
- return _stack.size();
- }
- int main()
- {
- string str[] = {"hello","world","I","Love","You!",":-)"};
- Stack stack(str,str+6);
- for (int i = 0; i < stack.size(); i++)
- {
- cout << stack[i] << " ";
- }
- cout << endl;
- string st;
- stack.peek(st);
- cout << "peek: " << st << endl;
- stack.pop(st);
- cout << "pop: " << st << endl;
- stack.push("MyLove");
- for (i = 0; i < stack.size(); i++)
- {
- cout << stack[i] << " ";
- }
- cout << endl;
- if (stack.empty())
- {
- cout << "no elem in stack!" << endl;
- }
- else
- {
- cout << "stack's elems are: " << endl;
- for (i = 0; i < stack.size(); i++)
- {
- cout << stack[i] << " ";
- }
- cout << endl;
- }
- return 0;
- }