c++ 常用buffer实现

1、一个buffer缓存简单实现

#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <malloc.h>

class Buffer
{
public:
    Buffer()
    {
        m_buf = (char *)malloc(m_incr);
        if (m_buf == nullptr)
        {
            return;
        }
        m_cap += m_incr;
        m_begin = m_end = 0;
    }
    ~Buffer()
    {
        free(m_buf);
        m_buf = nullptr;
    }
    int GetBegin() { return m_begin; }
    int GetEnd() { return m_end; }
    int GetCap() { return m_cap; }
    int GetLeft() { return (m_cap - m_end); }
    int ContentSize() { return (m_end - m_begin); }
    void Put(const char *c, int len);
    char *Get(int len);

private:
    char *m_buf{nullptr};
    int m_begin{0}; //buffer 内容开始
    int m_end{0};   //buffer 内容结束
    int m_cap{0};   //buffer 总量
    int m_incr{10};
};

void Buffer::Put(const char *c, int len)
{
    if (c == nullptr || len <&
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ring buffer(环形缓冲区)可以通过多种编程语言实现,以下是一些常用语言的实现示例: C++: ```cpp template<typename T, int capacity> class RingBuffer { private: std::array<T, capacity> buffer_; int head_ = 0; int tail_ = 0; int size_ = 0; public: void push(const T& item) { buffer_[tail_] = item; tail_ = (tail_ + 1) % capacity; if (size_ == capacity) { head_ = (head_ + 1) % capacity; } else { size_++; } } T& front() { return buffer_[head_]; } void pop() { head_ = (head_ + 1) % capacity; size_--; } bool empty() const { return size_ == 0; } int size() const { return size_; } }; ``` Java: ```java public class RingBuffer<T> { private T[] buffer_; private int head_ = 0; private int tail_ = 0; private int size_ = 0; @SuppressWarnings("unchecked") public RingBuffer(int capacity) { buffer_ = (T[]) new Object[capacity]; } public void push(T item) { buffer_[tail_] = item; tail_ = (tail_ + 1) % buffer_.length; if (size_ == buffer_.length) { head_ = (head_ + 1) % buffer_.length; } else { size_++; } } public T front() { return buffer_[head_]; } public void pop() { head_ = (head_ + 1) % buffer_.length; size_--; } public boolean empty() { return size_ == 0; } public int size() { return size_; } } ``` Python: ```python class RingBuffer: def __init__(self, capacity): self.buffer = [None] * capacity self.head = 0 self.tail = 0 self.size = 0 def push(self, item): self.buffer[self.tail] = item self.tail = (self.tail + 1) % len(self.buffer) if self.size == len(self.buffer): self.head = (self.head + 1) % len(self.buffer) else: self.size += 1 def front(self): return self.buffer[self.head] def pop(self): self.head = (self.head + 1) % len(self.buffer) self.size -= 1 def empty(self): return self.size == 0 def size(self): return self.size ``` 以上是一些简单的环形缓冲区实现示例,不同语言的实现可能会有差异,但基本原理都是一样的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值