头文件MyStack_vector.h
#pragma once
#include <vector>
#include <stdexcept>
template<typename T>
class MyStack {
private:
std::vector<T> elems;//容器
public:
MyStack();//默认构造
MyStack(MyStack<T> const&);//拷贝构造
MyStack<T>& operator=(MyStack<T> const&);//运算符=重载
void push(T const&);//入栈
void pop();//出栈
T top() const;//返回栈顶元素
bool empty() const { return elems.empty(); }//返回栈是否为空
};
#define __MYSTACK_VECTOR__
#include "MyStack_vector.cpp"
实现文件MyStack_vector.cpp
#ifdef __MYSTACK_VECTOR__
//默认构造
template<typename T>
inline
MyStack<T>::MyStack() {};
//拷贝构造
template<typename T>
inline
MyStack<T>::MyStack(MyStack<T> const& other_elems){}
//入栈
template<typename T>
inline
void MyStack<T>::push(T const& elem) {
elems.push_back(elem);
}
//出栈
template<typename T>
inline
void MyStack<T>::pop() {
if (elems.empty()) {
throw std::out_of_range("Stack<>::pop(): empty stack");
}
elems.pop_back();
}
//返回栈顶元素
template<typename T>
inline
T MyStack<T>::top() const {
if (elems.empty()) {
throw std::out_of_range("Stack<>::pop() empty stack");
}
return elems.back();
}
//运算符重载=
template<typename T>
inline
MyStack<T>& MyStack<T>::operator=(MyStack<T> const& other_elems) {}
#endif // __MYSTACK_VECTOR__
进行测试
#include <iostream>
#include <string>
#include <cstdlib>
#include "MyStack_vector.h"
int main()
{
//Mystack测试
{
//创建别名
typedef MyStack<int> IntStack;
typedef MyStack<std::string> StringStack;
try {
IntStack intStack;//元素类型为int的栈
StringStack stringStack;//元素类型为string的栈
//使用int栈
intStack.push(7);//把7入栈
std::cout << "intStack top is " << intStack.top() << std::endl;//返回栈顶元素
intStack.pop();//出栈
std::string isEmpty = (intStack.empty() == 1) ? "ture )" : "false )";
std::cout << "After MyStack<>::pop() intStack is empty now? ( "
<< isEmpty << std::endl;
//使用string栈
stringStack.push("hello");//把"hello"入栈
std::cout << "stringStack top is " << stringStack.top() << std::endl;//返回栈顶元素
stringStack.pop();//出栈
stringStack.pop();//故意出空栈,看看会发生什么
}
catch (std::exception const& ex) {
std::cerr << "Exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
}
}