STL源码剖析之stack

大家知道在程序设计里面,哪种数据结构使用率最高呢?答案是:栈。为什么呢?因为程序设计里面会存在的大量的函数调用,而函数的调用实质是使用了栈。今天就让我们来了解一下栈的底层实现吧~

栈是一种先进后出的数据结构,它只有一个出口,因此它允许在最顶端增加元素和删除元素。所以栈是不存在迭代器的,也就是说栈不存在遍历行为啦。

由于栈以底部的某个容器完成其所有的工作,所以我们可以把栈理解为“修改某数据结构的接口,从而形成了另一种事物”。因此栈是一种适配器。

栈的实现往往很简单,代码如下:

#include"stacktype.h"

template<typename T>
struct StackType {
	typedef T           Value_type;
	typedef size_t      Size_type;
	typedef T&          Reference;
	typedef const T&    Const_Reference;
};

#include"stack.h" 

template<typename T>
class Stack {
	friend bool operator==(const Stack<T>& stack1, const Stack<T>& stack2);
	friend bool operator<(const Stack<T>& stack1, const Stack<T>& stack2);
public:
	Stack() :arrays(nullptr) : tops(-1) {};
	Stack(const typename StackType<T>::Size_type n):arrays(new T[n]()), tops(-1) {};
	bool empty()const;
	typename StackType<T>::Size_type size()const;
	typename StackType<T>::Reference top()const;
	typename StackType<T>::Const_Reference top()const;
	void pop();
	void push(const T& value);
private:
	T* arrays;
	int tops;
};

#include"stack.cpp"

template<typename T>
bool operator==(const Stack<T>& stack1, const Stack<T>& stack2) {
	if (stack1.arrays == stack2.arrays)
		return true;
	else
		return false;
}

template<typename T>
bool Stack<T>::empty()const {
	if (tops == -1)
		return true;
	else
		return false;
}

template<typename T>
typename StackType<T>::Size_type Stack<T>::size()const {
	if (!empty()) {
		return tops;
	}
	else
		return 0;
}

template<typename T>
typename StackType<T>::Reference Stack<T>::top()const {
	return arrays[tops];
}

template<typename T>
typename StackType<T>::Const_Reference Stack<T>::top()const {
	return arrays[tops];
}

template<typename T>
void Stack<T>::pop() {
	if (!empty()) {
		--tops;
	}
}

template<typename T>
void Stack<T>::push(const T& value) {
	auto size = sizeof(arrays) / sizeof(arrays[0]);
	if (tops + 1 < size) {
		arrays[tops] = value;
		++tops;
	}
	else {
		auto _arrays = new T[2 * size]();
		for (int i = 0; i < size; ++i) {
			_arrays[i] = arrays[i];
		}
		arrays = _arrays;
		arrays[tops] = value;
		++tops;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值