算法4:定容栈C++实现
头文件:
#include <string> #include <vector> using namespace std; class FixedCapacityStackOfStrings { private: vector<string> a; int N; public: FixedCapacityStackOfStrings(int cap);
~FixedCapacityStackOfStrings(); bool isEmpty(); int size(); void push(string item); string pop(); };
源文件:
#include <iostrea>
#include <fstream>
#include <string> #include <vector> #include "FixedCapacityStackOfStrings.h" using namespace std; FixedCapacityStackOfStrings::FixedCapacityStackOfStrings(int cap) { a.resize(cap); N = 0; }
FixedCapacityStackOfStrings::~FixedCapacityStackOfStrings() {} bool FixedCapacityStackOfStrings::isEmpty() { return N == 0; } int FixedCapacityStackOfStrings::size() { return N; } void FixedCapacityStackOfStrings::push(string item) { a[N++] = item; } string FixedCapacityStackOfStrings::pop() { return a[--N]; } int main() { FixedCapacityStackOfStrings s(100); string file; ifstream tobe; cout << "输入文件名:"; cin >> file; tobe.open(file, ios::in); while (!tobe.eof()) { string item; tobe >> item; if (!item._Equal("-")) s.push(item); else if (!s.isEmpty()) cout << s.pop() << " "; } cout << "(" << s.size() << " left on stack)"; }