Kylin/DataStructure/StaticStack.h
2023-12-27 10:29:16 +08:00

41 lines
1.0 KiB
C++

#ifndef STATICSTACK_H
#define STATICSTACK_H
#include "Exception.h"
#include "Stack.h"
namespace Kylin {
template <typename T, size_t N>
class StaticStack : public Stack<T> {
public:
virtual void push(const T &value) {
if (m_size >= N) THROW_EXCEPTION(InvalidOperationException, "There is no space to push element...");
m_array[m_size] = value;
m_size++;
}
T pop() final {
if (m_size <= 0) THROW_EXCEPTION(InvalidOperationException, "There is no element in stack...");
auto value = top();
m_size--;
return value;
}
virtual T &top() {
if (m_size <= 0) THROW_EXCEPTION(InvalidOperationException, "There is no element in stack...");
return m_array[m_size - 1];
}
virtual void clear() { m_size = 0; }
virtual size_t size() const { return m_size; }
size_t capacity() const { return N; }
protected:
T m_array[N];
size_t m_size = 0;
};
} // namespace Kylin
#endif // STATICSTACK_H