本文实现了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 内存查看方法:meminfo\maps\smaps\status 文件解析

    linux 下面查看内存有多种渠道,比如通过命令 ps ,top,free 等,比如通过/proc系统,一般需要比较详细和精确地知道整机内存/某个进程内存的使用情况,最好通过/proc 系统,下面介绍 ...

  2. 6.DataFrame(列运算)

    from odps import ODPS from odps.df import DataFrame o = ODPS(access_id="LTAIBb3aOF3ghjek", ...

  3. 【原创】配置Windows Live Writer,写cnblogs博客

    20180115更新补充: 现在live writer已经改名open live writer了,需要去下载的到地址:http://openlivewriter.org/ 引言 以前写博客一般都是联网 ...

  4. 什么是web前端,全栈工程师就业前景怎么样?

    Web全栈工程师 什么是web前端? Web为你在浏览器.APP.应用程序等设备上提供直观界面,这些界面展现以及用户交互就是前端. 从2016年到2017年,web前端岗位从之前的爆发式增长变为平稳的 ...

  5. J.U.C并发框架源码阅读(十三)ThreadPoolExecutor

    基于版本jdk1.7.0_80 java.util.concurrent.ThreadPoolExecutor 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. U ...

  6. PostgreSQL(EXCEPT,INTERSECT)

    except 可以查看表一对表二不一样的数据,有点像是对表一进行表一表二交集的反集的交集,好绕: intersect 可以查看表一和表二一样的数据,求交集: select t1.name,t1.age ...

  7. kibana- Pie

    1. Visualize 新建图形 2. 选择图形类型 3. 选择索引 4. 设置Pie参数 5. 保存图形

  8. POJ 2836 Rectangular Covering(状压DP)

    [题目链接] http://poj.org/problem?id=2836 [题目大意] 给出二维平面的一些点,现在用一些非零矩阵把它们都包起来, 要求这些矩阵的面积和最小,求这个面积和 [题解] 我 ...

  9. Oracle数据库任何用户密码都能以sysdba角色登入

    * 本文相关环境:Windows 10,64位操作系统:Oracle 11gR2:toad for Oracle12.1 最近在学习Oracle数据库,使用Toad for Oracle来查看数据库的 ...

  10. mysql的load data,高速将文本文件,插入数据库中

    1语法 LOAD DATA [ LOW_PRIORITY | CONCURRENT ] [ LOCAL ] INFILE 'file_name.txt' [ REPLACE | IGNORE ] IN ...