Stack源码从0开始了解

本文详细解析了C++中Stack的源码实现,重点介绍了使用deque作为默认容器的情况。通过using关键字给类型指定别名,利用static_assert进行类型一致性检查,并探讨了default构造函数的作用。同时,讲解了empty、size、top、push和pop等关键操作的实现细节,特别是如何通过deque的成员函数来管理Stack的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

template <class _Ty, class _Container = deque<_Ty>>

temple<class _Ty>————通用模板类类,_Ty 为虚拟类型名 :"一类多用"

class _Container = deque<_Ty> 默认存放元素的容器 deque

    using value_type      = typename _Container::value_type;
    using reference       = typename _Container::reference;
    using const_reference = typename _Container::const_reference;
    using size_type       = typename _Container::size_type;
    using container_type  = _Container;

using在c++11以后有了一种新的作用,那就是与typedef一样,给类型指定别名

using 别名=类型;

static_assert(is_same_v<_Ty, value_type>, "container adaptors require consistent types")

static_assert关键字 —— static_assert(常量表达式,提示字符串)

如果第一个参数常量表达式的值为false,会产生一条编译错误,错误位置就是该static_assert语句所在行,第二个参数就是错误提示字符串

编译器在遇到一个static_assert语句时,通常立刻将其第一个参数作为常量表达式进行演算,但如果该常量表达式依赖于某些模板参数,则延迟到模板实例化时再进行演算,这就让检查模板参数成为了可能。

stack() = default;

=default语法表示默认存在构造函数 。

类内声明的时候使用=default时,函数被隐式声明为内联函数

当我们不想声明为内联函数的话,就在类外的定义处添加=default就好了

 _NODISCARD bool empty() const noexcept(noexcept(c.empty())) /* strengthened */ {
        return c.empty();
    }

    _NODISCARD size_type size() const noexcept(noexcept(c.size())) /* strengthened */ {
        return c.size();
    }

    _NODISCARD reference top() noexcept(noexcept(c.back())) /* strengthened */ {
        return c.back();
    }

    _NODISCARD const_reference top() const noexcept(noexcept(c.back())) /* strengthened */ {
        return c.back();
    }

  _NODISCARD:后面的语句出错使编译器发出警告

例:判断是否为空;返回 大小 ;返回top()(用deque.back()表示stack.top())

【不太确定】

    void push(const value_type& _Val) {
        c.push_back(_Val);
    }

    void push(value_type&& _Val) {
        c.push_back(_STD move(_Val));
    }

插入数据 ,deque的尾插

    void pop() noexcept(noexcept(c.pop_back())) /* strengthened */ {
        c.pop_back();
    }

删除deque的尾部元素,即删除栈的顶部元素 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值