[C++]stack源码解析

本文深入解析C++标准库中stack的实现,重点讲解其默认使用deque作为底层容器以及如何利用move语义。文章首先补充了关于enabled_if和条件编译的知识,然后展示了stack的源码,并提及了deque接口的相关内容。

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

stack源码解析

stack是默认使用deque(双头队列)来实现的。实际上如果使用结构体指针也是可以做到相同功能的。以下提供stack源码。重点学习其头文件的写法。

首先补充一点知识:

enabled_if:

template <bool Cond, class T = void> struct enable_if;
Enable type if condition is met
The type T is enabled as member type enable_if::type if Cond is true.

Otherwise, enable_if::type is not defined.

This is useful to hide signatures on compile time when a particular condition is not met, since in this case, the memberenable_if::type will not be defined and attempting to compile using it should fail.

It is defined with a behavior equivalent to:
1 template<bool Cond, class T = void> struct enable_if {};
2 template<class T> struct enable_if<true, T> { typedef T type; };

这是来自cplusplus的解释。就是说,Cond(即condition)一定要是true,才能通过编译。看例子,来具体分析:

而关于move的转移语义。具体看前文。右值引用和转移语义

// enable_if example: two ways of using enable_if
#include <iostream>
#include <type_traits>
// 1. the return type (bool) is only valid if T is an integral type:
template <class T>
typename std::enable_if<std::is_integral<T>::value,bool>::type
is_odd (T i) {return bool(i%2);}

// 2. the second template argument is only valid if T is an integral type:
template < class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even (T i) {return !bool(i%2);}

int main() {

    int i = 1;    // code does not compile if type of i is not integral

    std::cout << std::boolalpha;
    std::cout << "i is odd: " << is_odd(i) << std::endl;
    std::cout << "i is even: " << is_even(i) << std::endl;

    return 0;
}

而关于move的转移语义。具体看前文。右值引用和转移语义

源码

// -*- C++ -*-
//===---------------------------- stack -----------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#ifndef _LIBCPP_STACK
#define _LIBCPP_STACK

/*
    stack synopsis

namespace std
{

template <class T, class Container = deque<T>>
class stack
{
public:
    typedef Container                                container_type;
    typedef typename container_type::value_type      value_type;
    typedef typename container_type::reference       reference;
    typedef typename container_type::const_reference const_reference;
    typedef typename container_type::size_type       size_type;

protected:
    container_type c;

public:
    stack() = default;
    ~stack() = default;

    stack(const stack& q) = default;
    stack(stack&& q) = default;

    stack& operator=(const stack& q) = default;
    stack& operator=(stack&& q) = default;

    explicit stack(const container_type& c);
    explicit stack(container_type&& c);
    template <class Alloc> explicit stack(const Alloc& a);
    template <class Alloc> stack(const container_type& c, const Alloc& a);
    template <class Alloc> stack(container_type&& c, const Alloc& a);
    template <class Alloc> stack(const stack& c, const Alloc& a);
    template <class Alloc> stack(stack&& c, const Alloc& a);

    bool empty() const;
    size_type size() const;
    reference top();
    const_reference top() const;

    void push(const value_type& x);
    void push(value_type&& x);
    template <class... Args> void emplace(Args&&... args);
    void pop();

    void swap(stack& c) noexcept(noexcept(swap(c, q.c)));
};

template <class T, class Container>
  bool operator==(const stack<T, Container>& x, const stack<T, Container>& y);
template <class T, class Container>
  bool operator< (const stack<T, Container>& x, const stack<T, Container>& y);
template <class T, class Container>
  bool operator!=(const stack<T, Container>& x, const stack<T, Container>& y);
template <class T, class Container>
  bool operator> (const stack<T, Container>& x, const stack<T, Container>& y);
template <class T, class Container>
  bool operator>=(const stack<T, Container>& x, const stack<T, Container>& y);
template <class T, class Container>
  bool operator<=(const stack<T, Container>& x, const stack<T, Container>& y);

template <class T, class Container>
  void swap(stack<T, Container>& x, stack<T, Container>& y)
  noexcept(noexcept(x.swap(y)));

}  // std

*/

#include <__config>
#include <deque>

#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif

_LIBCPP_BEGIN_NAMESPACE_STD

template <class _Tp, class _Container = deque<_Tp> > class _LIBCPP_TYPE_VIS_ONLY stack;

template <class _Tp, class _Container>
_LIBCPP_INLINE_VISIBILITY
bool
operator==(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y);

template <class _Tp, class _Container>
_LIBCPP_INLINE_VISIBILITY
bool
operator< (const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y);

template <class _Tp, class _Container /*= deque<_Tp>*/>
class _LIBCPP_TYPE_VIS_ONLY stack
{
public:
    typedef _Container                               container_type;
    typedef typename container_type::value_type      value_type;
    typedef typename container_type::reference       reference;
    typedef typename container_type::const_reference const_reference;
    typedef typename container_type::size_type       size_type;

protected:
    container_type c;

public:
    _LIBCPP_INLINE_VISIBILITY
    stack()
        _NOEXCEPT_(is_nothrow_default_constructible<container_type>::value)
        : c() {}

    _LIBCPP_INLINE_VISIBILITY
    stack(const stack& __q) : c(__q.c) {}

#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    _LIBCPP_INLINE_VISIBILITY
    stack(stack&& __q)
        _NOEXCEPT_(is_nothrow_move_constructible<container_type>::value)
        : c(_VSTD::move(__q.c)) {}
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES

    _LIBCPP_INLINE_VISIBILITY
    stack& operator=(const stack& __q) {c = __q.c; return *this;}

#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    _LIBCPP_INLINE_VISIBILITY
    stack& operator=(stack&& __q)
        _NOEXCEPT_(is_nothrow_move_assignable<container_type>::value)
        {c = _VSTD::move(__q.c); return *this;}
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES

    _LIBCPP_INLINE_VISIBILITY
    explicit stack(const container_type& __c) : c(__c) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    _LIBCPP_INLINE_VISIBILITY
    explicit stack(container_type&& __c) : c(_VSTD::move(__c)) {}
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
    template <class _Alloc>
        _LIBCPP_INLINE_VISIBILITY
        explicit stack(const _Alloc& __a,
                       typename enable_if<uses_allocator<container_type,
                                                         _Alloc>::value>::type* = 0)
            : c(__a) {}
    template <class _Alloc>
        _LIBCPP_INLINE_VISIBILITY
        stack(const container_type& __c, const _Alloc& __a,
              typename enable_if<uses_allocator<container_type,
                                                _Alloc>::value>::type* = 0)
            : c(__c, __a) {}
    template <class _Alloc>
        _LIBCPP_INLINE_VISIBILITY
        stack(const stack& __s, const _Alloc& __a,
              typename enable_if<uses_allocator<container_type,
                                                _Alloc>::value>::type* = 0)
            : c(__s.c, __a) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    template <class _Alloc>
        _LIBCPP_INLINE_VISIBILITY
        stack(container_type&& __c, const _Alloc& __a,
              typename enable_if<uses_allocator<container_type,
                                                _Alloc>::value>::type* = 0)
            : c(_VSTD::move(__c), __a) {}
    template <class _Alloc>
        _LIBCPP_INLINE_VISIBILITY
        stack(stack&& __s, const _Alloc& __a,
              typename enable_if<uses_allocator<container_type,
                                                _Alloc>::value>::type* = 0)
            : c(_VSTD::move(__s.c), __a) {}
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES

    _LIBCPP_INLINE_VISIBILITY
    bool empty()     const      {return c.empty();}
    _LIBCPP_INLINE_VISIBILITY
    size_type size() const      {return c.size();}
    _LIBCPP_INLINE_VISIBILITY
    reference top()             {return c.back();}
    _LIBCPP_INLINE_VISIBILITY
    const_reference top() const {return c.back();}

    _LIBCPP_INLINE_VISIBILITY
    void push(const value_type& __v) {c.push_back(__v);}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
    _LIBCPP_INLINE_VISIBILITY
    void push(value_type&& __v) {c.push_back(_VSTD::move(__v));}
#ifndef _LIBCPP_HAS_NO_VARIADICS
    template <class... _Args>
        _LIBCPP_INLINE_VISIBILITY
        void emplace(_Args&&... __args)
        {c.emplace_back(_VSTD::forward<_Args>(__args)...);}
#endif  // _LIBCPP_HAS_NO_VARIADICS
#endif  // _LIBCPP_HAS_NO_RVALUE_REFERENCES
    _LIBCPP_INLINE_VISIBILITY
    void pop() {c.pop_back();}

    _LIBCPP_INLINE_VISIBILITY
    void swap(stack& __s)
        _NOEXCEPT_(__is_nothrow_swappable<container_type>::value)
    {
        using _VSTD::swap;
        swap(c, __s.c);
    }

    template <class T1, class _C1>
    friend
    bool
    operator==(const stack<T1, _C1>& __x, const stack<T1, _C1>& __y);

    template <class T1, class _C1>
    friend
    bool
    operator< (const stack<T1, _C1>& __x, const stack<T1, _C1>& __y);
};

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return __x.c == __y.c;
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator< (const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return __x.c < __y.c;
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return !(__x == __y);
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator> (const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return __y < __x;
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator>=(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return !(__x < __y);
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator<=(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
{
    return !(__y < __x);
}

template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
void
swap(stack<_Tp, _Container>& __x, stack<_Tp, _Container>& __y)
    _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
{
    __x.swap(__y);
}

template <class _Tp, class _Container, class _Alloc>
struct _LIBCPP_TYPE_VIS_ONLY uses_allocator<stack<_Tp, _Container>, _Alloc>
    : public uses_allocator<_Container, _Alloc>
{
};

_LIBCPP_END_NAMESPACE_STD

#endif  // _LIBCPP_STACK

最后补充deque接口

namespace std
{

template <class T, class Allocator = allocator<T> >
class deque
{
public:
    // types:
    typedef T value_type;
    typedef Allocator allocator_type;

    typedef typename allocator_type::reference       reference;
    typedef typename allocator_type::const_reference const_reference;
    typedef implementation-defined                   iterator;
    typedef implementation-defined                   const_iterator;
    typedef typename allocator_type::size_type       size_type;
    typedef typename allocator_type::difference_type difference_type;

    typedef typename allocator_type::pointer         pointer;
    typedef typename allocator_type::const_pointer   const_pointer;
    typedef std::reverse_iterator<iterator>          reverse_iterator;
    typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;

    // construct/copy/destroy:
    deque() noexcept(is_nothrow_default_constructible<allocator_type>::value);
    explicit deque(const allocator_type& a);
    explicit deque(size_type n);
    explicit deque(size_type n, const allocator_type& a); // C++14
    deque(size_type n, const value_type& v);
    deque(size_type n, const value_type& v, const allocator_type& a);
    template <class InputIterator>
        deque(InputIterator f, InputIterator l);
    template <class InputIterator>
        deque(InputIterator f, InputIterator l, const allocator_type& a);
    deque(const deque& c);
    deque(deque&& c)
        noexcept(is_nothrow_move_constructible<allocator_type>::value);
    deque(initializer_list<value_type> il, const Allocator& a = allocator_type());
    deque(const deque& c, const allocator_type& a);
    deque(deque&& c, const allocator_type& a);
    ~deque();

    deque& operator=(const deque& c);
    deque& operator=(deque&& c)
        noexcept(
             allocator_type::propagate_on_container_move_assignment::value &&
             is_nothrow_move_assignable<allocator_type>::value);
    deque& operator=(initializer_list<value_type> il);

    template <class InputIterator>
        void assign(InputIterator f, InputIterator l);
    void assign(size_type n, const value_type& v);
    void assign(initializer_list<value_type> il);

    allocator_type get_allocator() const noexcept;

    // iterators:

    iterator       begin() noexcept;
    const_iterator begin() const noexcept;
    iterator       end() noexcept;
    const_iterator end() const noexcept;

    reverse_iterator       rbegin() noexcept;
    const_reverse_iterator rbegin() const noexcept;
    reverse_iterator       rend() noexcept;
    const_reverse_iterator rend() const noexcept;

    const_iterator         cbegin() const noexcept;
    const_iterator         cend() const noexcept;
    const_reverse_iterator crbegin() const noexcept;
    const_reverse_iterator crend() const noexcept;

    // capacity:
    size_type size() const noexcept;
    size_type max_size() const noexcept;
    void resize(size_type n);
    void resize(size_type n, const value_type& v);
    void shrink_to_fit();
    bool empty() const noexcept;

    // element access:
    reference operator[](size_type i);
    const_reference operator[](size_type i) const;
    reference at(size_type i);
    const_reference at(size_type i) const;
    reference front();
    const_reference front() const;
    reference back();
    const_reference back() const;

    // modifiers:
    void push_front(const value_type& v);
    void push_front(value_type&& v);
    void push_back(const value_type& v);
    void push_back(value_type&& v);
    template <class... Args> void emplace_front(Args&&... args);
    template <class... Args> void emplace_back(Args&&... args);
    template <class... Args> iterator emplace(const_iterator p, Args&&... args);
    iterator insert(const_iterator p, const value_type& v);
    iterator insert(const_iterator p, value_type&& v);
    iterator insert(const_iterator p, size_type n, const value_type& v);
    template <class InputIterator>
        iterator insert(const_iterator p, InputIterator f, InputIterator l);
    iterator insert(const_iterator p, initializer_list<value_type> il);
    void pop_front();
    void pop_back();
    iterator erase(const_iterator p);
    iterator erase(const_iterator f, const_iterator l);
    void swap(deque& c)
        noexcept(allocator_traits<allocator_type>::is_always_equal::value);  // C++17
    void clear() noexcept;
};

template <class T, class Allocator>
    bool operator==(const deque<T,Allocator>& x, const deque<T,Allocator>& y);
template <class T, class Allocator>
    bool operator< (const deque<T,Allocator>& x, const deque<T,Allocator>& y);
template <class T, class Allocator>
    bool operator!=(const deque<T,Allocator>& x, const deque<T,Allocator>& y);
template <class T, class Allocator>
    bool operator> (const deque<T,Allocator>& x, const deque<T,Allocator>& y);
template <class T, class Allocator>
    bool operator>=(const deque<T,Allocator>& x, const deque<T,Allocator>& y);
template <class T, class Allocator>
    bool operator<=(const deque<T,Allocator>& x, const deque<T,Allocator>& y);

// specialized algorithms:
template <class T, class Allocator>
    void swap(deque<T,Allocator>& x, deque<T,Allocator>& y)
         noexcept(noexcept(x.swap(y)));

}  // std
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值