-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_stack_element.h
More file actions
57 lines (49 loc) · 1.34 KB
/
max_stack_element.h
File metadata and controls
57 lines (49 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifndef CPP_ALGORITHM_MAX_STACK_ELEMENT_H
#define CPP_ALGORITHM_MAX_STACK_ELEMENT_H
#include <stack>
#include <stdexcept>
namespace MaxStackElement
{
/**
* \brief Custom stack that stores the maximum element.
*/
class Stack
{
public:
bool Empty() const { return std::empty(element_with_cached_max_); }
int Max() const
{
if (Empty())
{
throw std::length_error("Empty stack!");
}
return element_with_cached_max_.top().max;
}
int Pop()
{
if (Empty())
{
throw std::length_error("Empty stack!");
}
const int pop_element = element_with_cached_max_.top().element;
element_with_cached_max_.pop();
return pop_element;
}
void Push(const int x)
{
element_with_cached_max_.emplace(ElementWithCachedMax{x, std::max(x, Empty() ? x : Max())});
}
private:
struct ElementWithCachedMax
{
int element;
int max;
};
/**
* \brief Caches the maximum element in the stack.
* \details Caches the maximum among the elements below the current element.
*/
std::stack<ElementWithCachedMax> element_with_cached_max_;
};
}
#endif