circular 基于std::array覆盖式

template<class _Ty, size_t _Size>
class circular
{
public:
    class iterator_circual
    {
    public:
    private:
        size_t _pos;
        const circular<_Ty, _Size>* _buf;
    public:
        iterator_circual(const circular<_Ty, _Size>* buf, size_t pos)
            : _buf(buf)
            , _pos(pos)
        {


        }
        iterator_circual(const iterator_circual& rhs)
            : _buf(rhs._buf)
            , _pos(rhs._pos)
        {
        }
        iterator_circual& operator=(iterator_circual rhs) 
        {
            std::swap(_buf, rhs._buf);
            std::swap(_pos, rhs._pos);
            return *this;
        }


        iterator_circual& operator++ ()
        {
            if (++_pos == _buf->_max)
                _pos = 0;
            if (_pos == _buf->_tail)
                _pos = -1;
            return *this;
        }
        bool operator==(const iterator_circual& rhs) const 
        {
            return _buf == rhs._buf && _pos == rhs._pos;
        }
        bool operator!=(const iterator_circual& rhs) const 
        {
            return !operator==(rhs);
        }
        _Ty operator * ()
        {
            return _buf->_v.at(_pos);
        }
    };


private:
    std::array<_Ty, _Size> _v;
    size_t _tail;
    size_t _head;
    size_t _max;
    size_t _cnt;
public:
    circular()
        : _tail(0)
        , _head(0)
        , _max(_Size)
        , _cnt(0)
    {


    }
    void push_back(_Ty x)
    {
        _v[_tail] = x;
        if (++_tail == _max)
        {
            _tail = 0;
        }
        if (_cnt < _max)
            ++_cnt;
        else
            ++_head;
        if (_head == _max)
            _head = 0;
    }


    iterator_circual begin()
    {
        return iterator_circual(this, _head);
    }
    iterator_circual end()
    {
        return iterator_circual(this, -1);
    }
};
基于std::array覆盖式的,只是简单的那种,比较好的还是github上完整类似stl的写法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值