Kylin/DataStructure/StaticQueue.h

49 lines
1.2 KiB
C
Raw Permalink Normal View History

2023-12-27 10:29:16 +08:00
#ifndef STATICQUEUE_H
#define STATICQUEUE_H
#include "Exception.h"
#include "Queue.h"
namespace Kylin {
template <typename T, size_t N>
class StaticQueue : public Queue<T> {
public:
T &head() override {
if (m_size <= 0) THROW_EXCEPTION(InvalidParameterException, "There is no element in queue...");
return m_space[m_front];
}
void enqueue(const T &value) override {
if (m_size >= N) THROW_EXCEPTION(InvalidParameterException, "There is no space...");
m_space[m_rear] = value;
m_rear = (m_rear + 1) % N;
m_size++;
}
T dequeue() override {
if (m_size <= 0) THROW_EXCEPTION(InvalidParameterException, "There is no element in queue...");
auto result = m_space[m_front];
m_front = (m_front + 1) % N;
m_size--;
return result;
}
virtual void clear() {
m_front = 0;
m_rear = 0;
m_size = 0;
}
size_t size() const noexcept override { return m_size; }
size_t capacity() const { return N; }
private:
T m_space[N];
size_t m_front = 0;
size_t m_rear = 0;
size_t m_size = 0;
};
} // namespace Kylin
#endif // STATICQUEUE_H