本文实现了STL中stack的大部分功能,同时添加了一些功能。

注意以下几点:

1.Stack是一种适配器,底层以vector、list、deque等实现

2.Stack不含有迭代器

在本例中,我添加了几项功能,包括不同类型stack之间的复制和赋值功能,可以实现诸如Stack<int, vector<int> >和Stack<double, list<double> >之间的复制和赋值,这主要依靠成员函数模板来实现。

为了更方便的实现以上功能,我添加了一个函数:

const_container_reference get_container() const

来获取内部容器的引用。

此外,标准库的stack不检查越界行为,我为stack添加了异常处理,当栈空时,执行pop或者top会抛出异常。这个异常类继承自Exception(见上篇文章),用来标示栈空。

详细代码如下:Exception的实现见:借助backtrace和demangle实现异常类Exception

#ifndef STACK_HPP_
#define STACK_HPP_ #include "Exception.h"
#include <deque> //栈空引发的异常
class EmptyStackException : public Exception
{
public:
EmptyStackException() :Exception("read empty stack") { }
}; template <typename T, typename Container = std::deque<T> >
class Stack
{
public:
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef Container container_type; //容器类型
typedef EmptyStackException exception_type; //异常类型
typedef typename Container::size_type size_type;
typedef Container &container_reference; //容器引用
typedef const Container& const_container_reference; explicit Stack(const container_type &cont = container_type()) :cont_(cont) { }
    //不同类型间实现复制
template <typename T2, typename Container2>
Stack<T, Container>(const Stack<T2, Container2> &s); //不同类型间进行赋值
template <typename T2, typename Container2>
Stack<T, Container> &operator=(const Stack<T2, Container2> &s); void push(const value_type &val) { cont_.push_back(val); }
void pop()
{
if(cont_.empty())
throw exception_type();
cont_.pop_back();
} reference top()
{
if(cont_.empty())
throw exception_type();
return cont_.back();
}
const_reference top() const
{
if(cont_.empty())
throw exception_type();
return cont_.back();
} bool empty() const { return cont_.empty(); }
size_type size() const { return cont_.size(); } //获取内部容器的引用
const_container_reference get_container() const
{ return cont_; } friend bool operator==(const Stack &a, const Stack &b)
{
return a.cont_ == b.cont_;
}
friend bool operator!=(const Stack &a, const Stack &b)
{
return a.cont_ != b.cont_;
}
friend bool operator<(const Stack &a, const Stack &b)
{
return a.cont_ < b.cont_;
}
friend bool operator>(const Stack &a, const Stack &b)
{
return a.cont_ > b.cont_;
}
friend bool operator<=(const Stack &a, const Stack &b)
{
return a.cont_ <= b.cont_;
}
friend bool operator>=(const Stack &a, const Stack &b)
{
return a.cont_ >= b.cont_;
} private:
Container cont_;
}; template <typename T, typename Container>
template <typename T2, typename Container2>
Stack<T, Container>::Stack(const Stack<T2, Container2> &s)
:cont_(s.get_container().begin(), s.get_container().end())
{ } template <typename T, typename Container>
template <typename T2, typename Container2>
Stack<T, Container> &Stack<T, Container>::operator=(const Stack<T2, Container2> &s)
{
if((void*)this != (void*)&s)
{
cont_.assign(s.get_container().begin(), s.get_container().end());
} return *this;
} #endif /* STACK_HPP_ */

测试代码如下:

#include "Stack.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <stdio.h>
using namespace std; int main(int argc, char const *argv[])
{ try
{
Stack<string, vector<string> > st;
st.push("foo");
st.push("bar"); Stack<string, list<string> > st2(st);
//st2 = st; while(!st2.empty())
{
cout << st2.top() << endl;
st2.pop();
} st2.pop(); //引发异常
}
catch (const Exception& ex)
{
fprintf(stderr, "reason: %s\n", ex.what());
fprintf(stderr, "stack trace: %s\n", ex.stackTrace());
} return 0;
}

标准库Stack的一种实现的更多相关文章

  1. C++ 异常机制分析(C++标准库定义了12种异常,很多大公司的C++编码规范也是明确禁止使用异常的,如google、Qt)

    阅读目录 C++异常机制概述 throw 关键字 异常对象 catch 关键字 栈展开.RAII 异常机制与构造函数 异常机制与析构函数 noexcept修饰符与noexcept操作符 异常处理的性能 ...

  2. 标准库priority_queue的一种实现

    优先级队列相对于普通队列,提供了插队功能,每次最先出队的不是最先入队的元素,而是优先级最高的元素. 它的实现采用了标准库提供的heap算法.该系列算法一共提供了四个函数.使用方式如下: 首先,建立一个 ...

  3. C++标准库(体系结构与内核分析)(侯捷第二讲)

    一.OOP和GP的区别(video7) OOP:面向对象编程(Object-Oriented programming) GP:泛化编程(Generic programming) 对于OOP来说,我们要 ...

  4. C++ 标准库类型-String,Vector and Bitset

    <C++ Primer 4th>读书摘要 最重要的标准库类型是 string 和 vector,它们分别定义了大小可变的字符串和集合.这些标准库类型是语言组成部分中更基本的那些数据类型(如 ...

  5. 关于标准库中的ptr_fun/binary_function/bind1st/bind2nd

    http://www.cnblogs.com/shootingstars/archive/2008/11/14/860042.html 以前使用bind1st以及bind2nd很少,后来发现这两个函数 ...

  6. Python内置模块与标准库

    Python内置模块就是标准库(模块)吗?或者说Python的自带string模块是内置模块吗? 答案是:string不是内置模块,它是标准库.也就是说Python内置模块和标准库并不是同一种东西. ...

  7. Python标准库:1. 介绍

    标准库包括了几种不同类型的库. 首先是那些核心语言的数据类型库,比方数字和列表相关的库.在核心语言手冊里仅仅是描写叙述数字和列表的编写方式,以及它的排列,而未定义它的语义. 换一句话说,核心语言手冊仅 ...

  8. C++标准库类模板(stack)和 队列(queue)

    在C++标准库(STL)中有栈和队列的类模板,因此可以直接使用 1.栈(stack):使用栈之前,要先包含头文件 : #include<stack> stack.push(elem); / ...

  9. 谈谈两种标准库类型---string和vector

    两种最重要的标准库---string和vector string和vector是两种最重要的标准库类型,string表示可变长的字符序列,vector存放的是某种给定类型对象的可变长序列. 一.标准库 ...

随机推荐

  1. Linux内核实践之tasklet机制【转】

    转自:http://blog.csdn.net/bullbat/article/details/7423321 版权声明:本文为博主原创文章,未经博主允许不得转载. 作者:bullbat 源代码分析与 ...

  2. (二十七)Linux的inode的理解

    一.inode是什么? 理解inode,要从文件储存说起. 文件储存在硬盘上,硬盘的最小存储单位叫做"扇区"(Sector).每个扇区储存512字节(相当于0.5KB). 操作系统 ...

  3. windows下修改Mysql5.7.11初始密码的图文教程

    参考:http://www.jb51.net/article/98481.htm [摘要:1.my-default.ini 更名my.ini 正在解压的目次上面复造my-default.ini一份更名 ...

  4. [BZOJ2152]聪聪可可 点分治/树形dp

    2152: 聪聪可可 Time Limit: 3 Sec  Memory Limit: 259 MB Submit: 3602  Solved: 1858 [Submit][Status][Discu ...

  5. 找出数字数组中最大的元素(使用Math.max函数)

    从汤姆大叔的博客里看到了6个基础题目:本篇是第1题 - 找出数字数组中最大的元素(使用Match.max函数) 从要求上来看,不能将数组sort.不能遍历.只能使用Math.max,所以只能从java ...

  6. (4)oracle连接工具和配置监听

    一.SQL PLUS sql plus 是oracle最常用的命令行工具,启动sqlplus工具的方法有两种 1. 是在安装好的oracle开始程序的路径下运行程序 点击运行弹出此界面 2 .是在cm ...

  7. Codeforces 570D - Tree Requests(树上启发式合并)

    570D - Tree Requests 题意 给出一棵树,每个节点上有字母,查询 u k,问以 u 为根节点的子树下,深度为 k 的所有子节点上的字母经过任意排列是否能构成回文串. 分析 一个数组 ...

  8. Longest Common Substring($LCS$)

    Longest Common Substring(\(LCS\)) 什么是子序列? 子序列就是某一个序列的不连续的一部分. 如图, \(abcde\)就是图中序列的一个子序列. 公共子序列 公共子序列 ...

  9. 洛谷——P1147 连续自然数和

    P1147 连续自然数和 题目描述 对一个给定的自然数M,求出所有的连续的自然数段,这些连续的自然数段中的全部数之和为M. 例子:1998+1999+2000+2001+2002 = 10000,所以 ...

  10. elasticsearch REST api

    elasticsearch REST api========================================命令模式:<REST Verb> /<Index>/ ...