c++模板:用vector实现简单的stack

c++模板:用vector实现简单的stack,第1张

c++模板:用vector实现简单的stack

头文件MyStack_vector.h

#pragma once
#include 
#include 

template
class MyStack {
private:
	std::vector elems;//容器

public:
	MyStack();//默认构造
	MyStack(MyStack const&);//拷贝构造

	MyStack& operator=(MyStack 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
inline
MyStack::MyStack() {};

//拷贝构造
template
inline
MyStack::MyStack(MyStack const& other_elems){}

//入栈
template
inline
void MyStack::push(T const& elem) {
	elems.push_back(elem);
}

//出栈
template
inline
void MyStack::pop() {
	if (elems.empty()) {
		throw std::out_of_range("Stack<>::pop(): empty stack");
	}
	elems.pop_back();
}

//返回栈顶元素
template
inline
T MyStack::top() const {
	if (elems.empty()) {
		throw std::out_of_range("Stack<>::pop() empty stack");
	}
	return elems.back();
}

//运算符重载=
template
inline
MyStack& MyStack::operator=(MyStack const& other_elems) {}

#endif // __MYSTACK_VECTOR__

进行测试

#include 
#include 
#include 
#include "MyStack_vector.h"

int main()
{
    //Mystack测试
    {
        //创建别名
        typedef MyStack IntStack;
        typedef MyStack 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;
        }
    }

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3991700.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存