下午好 !
我正在尝试制作某种圆形堆栈。它应该像一个普通的 LIFO 堆栈,但没有明显的限制。它应该消除或跳过当时引入的第一个元素,而不是达到它的最大容量!
例如:
假设我们有一个包含 3 个元素的堆栈:stack[3]
我们通过“推”里面的 3 个元素来填充它:push[a], push[b], push[c]
.
但随后我们将要添加第 4 个和第 5 个元素:push[d], push[e]
.
标准堆栈会说堆栈达到了它的限制,它不能再添加任何元素。
但我想要一个循环堆栈,它可以消除或跳过a
and b
、记住c
、d
ande
和输出e
, d
and c
;
该项目是在 ESP32 上的 PlatformIO 中完成的,所以我无法访问 C++ STL,即使我有,我认为只为 1 个堆栈编译这么大的库是没有意义的。即使有一段时间我认为我应该编译一个应该让我访问stack
or的类似库deque
,那个时间已经过去了,因为现在我觉得自己像一个无法解决数学问题的白痴。这已经困扰了我一个多星期了。
我设法在网上找到的是以下 FIFO 循环缓冲区:
class circular_buffer {
public:
explicit circular_buffer(size_t size) :
buf_(std::unique_ptr<T[]>(new T[size])),
max_size_(size)
{
}
void put(T item)
{
std::lock_guard<std::mutex> lock(mutex_);
buf_[head_] = item;
if(full_) {
tail_ = (tail_ + 1) % max_size_;
}
head_ = (head_ + 1) % max_size_;
full_ = head_ == tail_;
}
T get()
{
std::lock_guard<std::mutex> lock(mutex_);
if(empty())
{
return T();
}
//Read data and advance the tail (we now have a free space)
auto val = buf_[tail_];
full_ = false;
tail_ = (tail_ + 1) % max_size_;
return val;
}
void reset()
{
std::lock_guard<std::mutex> lock(mutex_);
head_ = tail_;
full_ = false;
}
bool empty() const
{
//if head and tail are equal, we are empty
return (!full_ && (head_ == tail_));
}
bool full() const
{
//If tail is ahead the head by 1, we are full
return full_;
}
size_t capacity() const
{
return max_size_;
}
size_t size() const
{
size_t size = max_size_;
if(!full_)
{
if(head_ >= tail_)
{
size = head_ - tail_;
}
else
{
size = max_size_ + head_ - tail_;
}
}
return size;
}
private:
std::mutex mutex_;
std::unique_ptr<T[]> buf_;
size_t head_ = 0;
size_t tail_ = 0;
const size_t max_size_;
bool full_ = 0;
};
在过去的 3 天里,我一直在修补它,但我无法让它按照我想要的方式工作。它是一个 FIFO 结构,将打印a
, b
,c
或c
, d
, e
。
在这种情况下,我希望它从上到下,从头到尾打印,但我无法弄清楚。