循环缓冲区队列

#include <iostream>

using namespace std;

template<typename T, size_t N>
class ring_buffer {
public:
  ring_buffer() : read_pos_(0), write_pos_(0) {}
  bool empty() const {
    return read_pos_ == write_pos_;
  }

  bool full() const {
    if (write_pos_ == N || write_pos_ < read_pos_) {
      return true;
    }

    return false;
  }

  void push_back(const T& t) {
    if (write_pos_ == N) {
      pop_front();
      write_pos_ = 0;
    }

    data_[write_pos_++] = t;
  }

  T& front() {
    return data_[read_pos_];
  }

  void pop_front() {
    read_pos_ = (read_pos_ + 1) % N;
  }
private:
  T data_[N];
  size_t read_pos_;
  size_t write_pos_;

};

int main() {
  ring_buffer<int, 5> ring;
  std::cout << "is empty: " << ring.empty() << std::endl;
  std::cout << "is full: " << ring.full() << std::endl;

  ring.push_back(1);
  ring.push_back(2);
  ring.push_back(3);
  ring.push_back(4);
  ring.push_back(5);
  std::cout << "is full: " << ring.full() << std::endl;
  std::cout << "front: " << ring.front() << std::endl;
  ring.push_back(6);
  std::cout << "front: " << ring.front() << std::endl;
  ring.pop_front();
  std::cout << "front: " << ring.front() << std::endl;

  return 0;
}

全部评论
灵均coding
点赞 回复 分享
发布于 2023-08-19 15:06 北京

相关推荐

评论
1
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务