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;
	}
}

发布了78 篇原创文章 · 获赞 11 · 访问量 5087

猜你喜欢

转载自blog.csdn.net/qq_43145594/article/details/104148556