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的写法
circular 基于std::array覆盖式
最新推荐文章于 2024-02-29 17:28:17 发布