- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_stack_element.h
More file actions
Latest commit
57 lines (49 loc) · 1.34 KB
/
Copy pathmax_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
#defineCPP_ALGORITHM_MAX_STACK_ELEMENT_H
#include<stack>
#include<stdexcept>
namespaceMaxStackElement
{
/**
* \brief Custom stack that stores the maximum element.
*/
classStack
{
public:
boolEmpty() const { returnstd::empty(element_with_cached_max_); }
intMax() const
{
if (Empty())
{
throwstd::length_error("Empty stack!");
}
return element_with_cached_max_.top().max;
}
intPop()
{
if (Empty())
{
throwstd::length_error("Empty stack!");
}
constint pop_element = element_with_cached_max_.top().element;
element_with_cached_max_.pop();
return pop_element;
}
voidPush(constint x)
{
element_with_cached_max_.emplace(ElementWithCachedMax{x, std::max(x, Empty() ? x : Max())});
}
private:
structElementWithCachedMax
{
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