模板类下压栈c++
FixedCapacityStackOfStrings.h
using namespace std; #include <string> #include <vector> template <class Type> class FixedCapacityStackOfStrings { private: vector<Type> a; int N; public: FixedCapacityStackOfStrings(int cap); ~FixedCapacityStackOfStrings(); bool isEmpty(); int size(); void push(Type item); Type pop(); };
FixedCapacityStackOfStrings.cpp
#include "FixedCapacityStackOfStrings.h" #include <iostream> #include <string> #include <vector> using namespace std; template <class Type> FixedCapacityStackOfStrings<Type>::FixedCapacityStackOfStrings(int cap) { a.resize(cap); N = 0; } template <class Type> FixedCapacityStackOfStrings<Type>::~FixedCapacityStackOfStrings() {} template <class Type> bool FixedCapacityStackOfStrings<Type>::isEmpty() { return N == 0; } template <class Type> int FixedCapacityStackOfStrings<Type>::size() { return N; } template <class Type> void FixedCapacityStackOfStrings<Type>::push(Type item) { a[N++] = item; } template <class Type> Type FixedCapacityStackOfStrings<Type>::pop() { return a[--N]; }
main.cpp
#pragma once #include "FixedCapacityStackOfStrings.cpp" #include <string> #include <iostream> #include <fstream> using namespace std; void test() { FixedCapacityStackOfStrings<string> f(100); string file; ifstream tobe; cout << "输入文件名:"; cin >> file; tobe.open(file, ios::in); while (!tobe.eof()) { string item; tobe >> item; if (!item._Equal("-")) f.push(item); else if (!f.isEmpty()) cout << f.pop() << " "; } cout << "(" << f.size() << " left on stack)"; } int main() { test(); }
tobe.txt
to be or not to - be - - that - - - is